AngularJS directives attributes access from the controller

后端 未结 6 474
梦如初夏
梦如初夏 2021-01-31 15:31

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

6条回答
  •  猫巷女王i
    2021-01-31 16:22

    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: '

    {{text}} This will run fine!

    ', 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 }] }; });

提交回复
热议问题