I'm trying to use a directive in Angularjs in order to check if a user is themself in order to change the template accordingly.
For instance
<li is-self >
<a ng-show="logged_in" ng-href="/users/{{user.public_id}}"> Settings </a>
</li>
Admittedly this may not be the best approach to this problem, however I can't think of a better way to do it at the moment.
The problem I am having however is that I can not do an http request within the directive, thus I had to put it in a controller and reference it as a scope function i.e.
user_controller
$scope.isSelf = ->
$http({method: 'GET', url: '/is_self/' + $routeParams.id}).
success((data, status, headers, config) ->
if data
$scope.logged_in = true
).
error((data, status, headers, config) ->
console.log(data)
)
user_module
userModule.directive('isSelf', () ->
link: ($scope) ->
$scope.isSelf()
This technique poses a problem however, because the directive is being used across multiple files and multiple controllers. I think the solution that would be most appropriate would be just doing the request within the directive but that doesn't work because you can't seem to pass $http into it.
My ideal solution would be a combination of what I had like
userModule.directive('isSelf', () ->
link: ($scope, $http) ->
$http({method: 'GET', url: '/is_self/' + "3f8686589ad"}).
success((data, status, headers, config) ->
if data
$scope.logged_in = true
).
error((data, status, headers, config) ->
console.log(data)
)
)
I am obviously fairly new to the framework, so any help would be greatly appreciated.
Okay guys, I found the solution. Here it is for those who have the same problem.
Okay so after some more tinkering I realized that I guess I was going about it in the wrong way. I instead used a service per the suggestion below, here's the final code if anyone has the same problem and was wondering.
Module
userModule = angular.module('users', ["ngResource"])
userModule.factory('User', ['$resource', '$http', ($resource, $http) ->
User = $resource "/users/:id", id: "@id",
update: method: "PUT"
destroy: method: "DELETE"
User::isSelf = (id, cb) ->
$http.get('/is_self/' + id).success (data) ->
if data
cb true
User
])
Controller
StatsShowCtrl = ($scope, $location, $routeParams, User) ->
User.get id: $routeParams.id, (user) ->
self.original = user
$scope.user = new User(self.original)
$scope.user.isSelf $routeParams.id, (self) ->
if self
$scope.logged_in = true
HTML
<li ng-show="logged_in"> <a ng-href="/users/{{user.public_id}}"> Settings </a></li>