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

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

问题描述

我试图访​​问控制器功能指令的属性。然而,我访问它的时候,它是不明确的。我注意到,如果我做一个简单的定时器它的作品。有只有指令后执行code的方式,它的范围是准备和设置使用?

我做了一个拨弄它。请确保您的控制台打开。 http://jsfiddle.net/paulocoelho/uKA2L/1/

下面是code,我使用的小提琴:

 < D​​IV NG-应用=testApp>
    < testcomponent文本=你好!>< / testcomponent>
< / DIV>

  VAR模块= angular.module('testApp',[])
    .directive('testcomponent',函数(){
    返回{
        限制:'E',
        模板:'< D​​IV>< P> {{文本}}这将会运行得很好! < / P>< / DIV>,
        范围: {
            文本:@Text
        },
        控制器:函数($范围,$元素){
            的console.log($ scope.text); //这会返回undefined
            的setTimeout(函数(){
                的console.log($ scope.text); //这将返回的实际值...
            },1000);
        },
        链接:功能($范围,$元,$ ATTRS){
            的console.log($ scope.text);
            的setTimeout(函数(){
                的console.log($ scope.text);
            },1000);
        }
    };
});


解决方案

什么工作原理是,如果设置

  scope.text = attrs.text;

联和控制器的功能内。

请参阅小提琴: http://jsfiddle.net/JohannesJo/nm3FL/2/

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

解决方案

What works is, if you set

scope.text = attrs.text;

inside the linking and the controller functions.

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

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

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