页面控制器方法是否有办法覆盖指令方法?

时间:2015-05-12 20:00:14

标签: angularjs controller directive

页面控制器是否可以覆盖指令的行为?

所以,

scope.doSomething = function() {
   // whatever in the directive
};

$scope.doSomething = function() {
   // do a different whatever than the directive
};

基本上,该指令对每个案例都有相同的行为,但只有一个(覆盖)行为是“不做任何事”,只是显示。

1 个答案:

答案 0 :(得分:1)

您的指令应使用其属性为其可能需要的任何其他参数定义接口。

angular.module('theApp', []).directive('someDirective', function () {
    return {
        scope: {
            formattingFn: '=',
        },
        template: "<div> {{viewableData}} </div>",
        link: function(scope){
            // Don't do this in the real world - make sure it quacks first:
            scope.viewableData = (scope.formattingFn || defaultFormat)("Hello World");
        }
    };
    function defaultFormat(data){ 
        return data; 
    }
});

然后将使用哪两种方式,前者将使用您的功能,后者则不会:

<div some-directive formatting-fn="doSomething"></div>
<div some-directive></div>

我们的想法是通过指令scope

构建一个接口