首页 > angular 指令里直接赋值是什么用法

angular 指令里直接赋值是什么用法

假设我们自定义一个指令

angular.module.directive('sayHello', function(){
    return {
        restrict: 'A',
        ...
    }
})

偶然间看到过这样的写法

<div say-hello="sth"></div>

我记得一般都是在指令里指定scope选项,然后定义一个开头是=的内部属性,从DOM里把数据传递到指令指令里面.
请问直接在指令sayHello上赋值,那么controller里的$scope.sth会被传到指令里吗?

或者这种用法的原理是什么,求解答


直接写=的话会。


directivelink中可以获得DOM属性值attrs
想要监听attrs改变的话,可以自定义一个watch
比如你这个

angular.module.directive('sayHello', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$watch(attrs.sayHello, function(value) {
                console.log("say-hello", value);
            });
        }
    }
})

angularjs的Developer Guide里有介绍

【热门文章】
【热门文章】