Angularjs:自定义指令范围未定义

时间:2016-06-01 21:09:07

标签: angularjs angularjs-directive

我正在创建一个处理属性值数据的指令。该指令仅用作元素的属性。所以现在我只想在调用它时运行一个函数

指令调用如下:

<div rest="accounts">
    {{testing}}
</div>

指令定义如下:

app.directive("rest", [function(){
    return {
        restrict: 'A',
        scope: {
            rest: '='
        },
        link: function(scope, element, attrs, ctrl) {
            console.log(scope);
        }
    };
}])

每当我使用该指令时,日志会将属性rest显示为undefined ..帐户只是一个字符串,因为我想首先测试该指令,但我还不知道为什么它总是未定义,即使使用$watch这样:

app.directive("rest", [function(){
    return {
        restrict: 'A',
        scope: {
            rest: '='
        },
        link: function(scope, element, attrs, ctrl) {
            scope.$watch('rest', function(data){
                console.log(data); //Still undefined
            });
        }
    };
}])

1 个答案:

答案 0 :(得分:1)

用于传递值的方法是传递变量引用而不是字符串值。

在HTML中使用rest="accounts",范围中的=意味着双向绑定,其中内部属性scope.rest绑定到外部属性$scope.accounts

如果始终打算传递字符串,则应在scope属性中使用@。这意味着rest与字符串值之间的单向绑定。

您也可以在不定义$scope.accounts的情况下使用指令,方法是将您的值作为字符串文字提供,即rest="'accounts'"。但是,由于嵌套引号的繁琐性,这种形式应该谨慎使用。

相关问题