AngularJS指令属性来自控制器的访问 [英] AngularJS directives attributes access from the controller

查看:193
本文介绍了AngularJS指令属性来自控制器的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问控制器功能中的指令的属性。但是,当我访问它时,它是未定义的。我注意到,如果我做一个简单的计时器它工作。有没有办法在指令之后执行代码,并且它的范围已经准备好并设置为使用?

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?

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

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);
        }
    };
});


推荐答案

如果您设置

scope.text = $attrs.text;

内部链接和控制器功能。这只会在最初工作,因为没有2数据绑定。您可以使用 $ attrs.observe

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

查看小提琴: http://jsfiddle.net/JohannesJo / nm3FL / 2 /

这篇关于AngularJS指令属性来自控制器的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆