简体   繁体   中英

Directive scope undefined in controller

I am trying to make an http request in my controller, but my $scope.dataSource comes back as undefined , and I am not sure why. I build the directive like this:

app.directive('users', function(){
    return {
        restrict: 'E',
        templateUrl: '/templates/dashboard/config/users.html',
        scope: {
            dataSource: '@'
        },
        controller: function($scope, $http){
            $http({
                url: $scope.dataSource
            }).success(function(data){
                $scope.data = data;
            });
        }
    };
});

And the html like this, but it doesn't run the ajax request because the $scope.dataSource is undefined .

<users class="col-sm-4" data-source="/data/users.json"></users>

You don't need a controller you need a link function and pass the scope and $http to it.

app.directive('users', function($http){
    return {
        restrict: 'E',
        templateUrl: '/templates/dashboard/config/users.html',
        scope: {
            dataSource: '@'
        },
        transclude: true,
        link: function(scope, elem, attrs){
            $http({
                url: scope.dataSource
            }).success(function(data) {
                $parent.$scope.data = data; // where data is a model in parent controller.
            });
        }
    };
});

Move it to a watch function:

app.directive('users', function($http) {
    return {
        restrict: 'E',
        templateUrl: '/templates/dashboard/config/users.html',
        scope: {
            source: '@'
        },
        link: function($scope){
            $scope.watch('source', function(source) {
              if (dataSource !== undefined) {
                $http({
                    url: source
                }).success(function(data){
                    $scope.data = data;
                });
              }
            });
        }
    };
});

Using $attrs allows me to get the value like this:

app.directive('users', function(){
    return {
        restrict: 'E',
        templateUrl: '/templates/dashboard/config/users.html',
        scope: {
            dataSource: '@'
        },
        controller: function($scope, $http, $attrs){
            $http({
                url: $attrs.source
            }).success(function(data){
                $scope.data = data;
            });
        }
    };
});

I still use dataSource in the scope and html, but use $attrs.source in the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM