小编edu*_*dur的帖子

AngularJS指令属性来自控制器的访问

我试图在控制器函数中访问指令的属性.但是,当我访问它时,它是未定义的.我注意到如果我做一个简单的计时器就行了.有没有办法只在指令执行后才能执行代码,并且它的范围已准备好并设置为使用?

我弄了一个小提琴.确保您的控制台已打开.http://jsfiddle.net/paulocoelho/uKA2L/1/

这是我在小提琴中使用的代码:

<div ng-app="testApp" >
    <testcomponent text="hello!"></testcomponent>
</div>
Run Code Online (Sandbox Code Playgroud)
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);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

javascript events controller angularjs angularjs-directive

37
推荐指数
4
解决办法
6万
查看次数