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

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

问题描述

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

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

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

<div ng-app="testApp" ><testcomponent text="hello!"></testcomponent>

var module = angular.module('testApp', []).directive('testcomponent', function () {返回 {限制:'E',模板:'

{{text}} 这将运行良好!</p></div>',范围: {文字:'@文字'},控制器:函数($scope,$element){控制台日志($scope.text);//这将返回未定义设置超时(函数(){控制台日志($scope.text);//这将返回实际值...}, 1000);},链接:函数($scope,$element,$attrs){控制台日志($scope.text);设置超时(函数(){控制台日志($scope.text);}, 1000);}};});

解决方案

有效的是,如果你设置

scope.text = $attrs.text;

在链接和控制器功能中.这只会在最初有效,因为没有 2way-databinding.不过,您可以使用 $attrs.observe.

见小提琴: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. 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/

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

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