AngularJS directives attributes access from the controller

扶醉桌前 提交于 2019-12-03 04:08:35

问题


I am trying to access the attributes of a directive in the controller function. However, by the time I access it, it is undefined. I noticed that if I do a simple timer it works. Is there a way to execute code only after the directive and it's scopes are ready and set to be used?

I made a fiddle with it. Make sure your console is open. http://jsfiddle.net/paulocoelho/uKA2L/1/

Here is the code I am using in the fiddle:

<div ng-app="testApp" >
    <testcomponent text="hello!"></testcomponent>
</div>
var module = angular.module('testApp', [])
    .directive('testcomponent', function () {
    return {
        restrict: 'E',
        template: '<div><p>{{text}} This will run fine! </p></div>',
        scope: {
            text: '@text'
        },
        controller: function ($scope, $element) {
            console.log($scope.text); // this will return undefined
            setTimeout(function () {
                console.log($scope.text);    // this will return the actual value...
            }, 1000);
        },
        link: function ($scope, $element, $attrs) {
            console.log($scope.text);
            setTimeout(function () {
                console.log($scope.text);
            }, 1000);
        }
    };
});

回答1:


What works is, if you set

scope.text = $attrs.text;

inside the linking and the controller functions. This will only work initially, as there is no 2way- databinding. You can use $attrs.observe though.

See fiddle: http://jsfiddle.net/JohannesJo/nm3FL/2/




回答2:


In an isolated scope, a local scope property defined with '@' can not be accessed in the linking function. As @remigio already mentioned, such local scope properties are undefined at that point. $attrs.$observe() or $scope.$watch() must be used to asynchronously obtain the (interpolated) value.

If you are passing a constant value in the attribute, (i.e., no interpolation required, i.e., the attribute's value doesn't contain any {{}}s) there is no need for '@' or $observer or $watch. You can use $attrs.attribute_name once as @hugo suggests, or if you are passing a number or a boolean and you want to get the proper type, you can use $scope.$eval($attrs.attribute_name) once.

If you use '=' to databind a local scope property to a parent scope property, the value of the property will be available in the linking function (no need for $observe or $watch or $eval).




回答3:


Since Angular 1.3, you can use bindToController. Here is a sample on how I use it. Here, I add the attribute to scope and then use bindToController to use that inside the controller:

var module = angular.module('testApp', [])
    .directive('testcomponent', function () {
    return {
        restrict: 'E',
        template: '<div><p>{{text}} This will run fine! </p></div>',
        scope: {
            text: '@text'
        },
        controller: function () {
            console.log(this.text);
        },
        controllerAs: 'vm',
        bindToController: true
    };
});

Angular 1.3 introduces a new property to the directive definition object called bindToController, which does exactly what it says. When set to true in a directive with isolated scope that uses controllerAs, the component’s properties are bound to the controller rather than to the scope. That means, Angular makes sure that, when the controller is instantiated, the initial values of the isolated scope bindings are available on this, and future changes are also automatically available.




回答4:


Instead using $scope to get directive attributes value, personally i prefer using $attrs for the controller function, or just attrs at 3rd parameter of the link function. I have no problem when get the attributes value from a controller by following code without timeout :

var module = angular.module('testApp', [])
    .directive('testcomponent', function () {
    return {
    restrict: 'E',
    template: '<div><p>{{text}} This will run fine! </p></div>',
    scope: {
        text: '@text'
    },
    controller: ['$scope','$attrs', function ($scope, $attrs) {
        console.log($attrs.text); // just call to the $attrs instead $scope and i got the actual value
        $scope.text = $attrs.text; //assign attribute to the scope
    }]
    };
});



回答5:


The link function is called before the $digest loop, at that moment scope variables are undefined. Look at this chapter and this other to understand how the link function operates. You only use the link function to define watches and/or behaviors for the directive, not to manipulate the model, this is done in controllers.




回答6:


If you are accessing this value from your directive to insert in your view using a directive you can access this attribute using the $compile api and doing something like this

var string = "<div> " + scope.text + "</div>";
$compile(string)(scope, function(cloned, scope){
       element.append(cloned);
});


来源:https://stackoverflow.com/questions/15151116/angularjs-directives-attributes-access-from-the-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!