Angular $ http request inside directive

I am trying to use a directive in Angularjs to check if the user is himself in order to change the template accordingly.

for example

    <li is-self >
        <a  ng-show="logged_in" ng-href="/users/{{user.public_id}}"> Settings </a>
    </li>    

      

Admittedly, this is not the best approach to this problem, however I cannot think of a better way to do this at the moment.

However, the problem is that I cannot make the HTTP request in the directive, so I had to put it in a controller and refer to 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 method poses a problem because the directive is used for multiple files and multiple controllers. I think the solution that would be most appropriate would be to simply execute the request in the directive, but that doesn't work because you can't pass $ http to it.

My ideal solution would be a combination of what I liked

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'm obviously completely new to structure, so any help would be greatly appreciated.

+3


source to share


1 answer


Ok guys I found a solution. Here it is for those who have the same problem.

Okay, after doing a little bit of work, I realized that I think I did the wrong thing. I used the service suggested below instead, here is the final code in case 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>

      

-1


source







All Articles