加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular:使用’@’定义的局部范围属性无法从链接

发布时间:2020-12-17 17:40:14 所属栏目:安全 来源:网络整理
导读:当我试图定义一些局部范围属性时,我发现用“@”定义的属性不能直接在链接函数中访问,而那些用“=”或“”定义的属性不是这种情况. 这是我写的简单指令(jsfiddle): angular.module('test',[]) .controller('testCtrl',function($scope) { $scope.count1 = 5;
当我试图定义一些局部范围属性时,我发现用“@”定义的属性不能直接在链接函数中访问,而那些用“=”或“&”定义的属性不是这种情况.

这是我写的简单指令(jsfiddle):

angular.module('test',[])
    .controller('testCtrl',function($scope) {
        $scope.count1 = 5;
    })
    .directive('testDir',function() {
        return {
            restrict: 'A',scope: {
                count: '=',readonly: '@'
            },link: function (scope,elem,attrs) {

                console.log('Outside has count? '+('count' in scope));
                console.log('Outside has readonly? '+('readonly' in scope));

                scope.$watch('count',function(value){
                    console.log('Inside has count? '+('count' in scope));
                    console.log('Inside has readonly? '+('readonly' in scope));
                    elem.text(value);
                });
            }
        };
});

输出是:

Outside has ‘count’? true

Outside has ‘readonly’? false

Inside has ‘count’? true

Inside has ‘readonly’? true

我不知道为什么scope.readonly(@)没有在范围之外定义.$watch函数虽然不是scope.count(=)的情况?

解决方法

这实际上是从 angular doc引用的预期结果:

… during the linking phase the interpolation hasn’t been evaluated yet and so the value is at this time set to undefined.

如果要获取属性的值,可以使用$observe或attrs.readonly:

link: function (scope,attrs) {
    ...

    console.log('readonly = ' + attrs.readonly);

    attrs.$observe('readonly',function(value) {
        console.log('readonly = ' + value);
    });

    ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读