对角度指令应用作用域并调用对象函数

applying scopes on angular directives and calling object function

本文关键字:调用 对象 函数 作用域 应用 指令      更新时间:2023-09-26

此代码运行良好,并使用父控制器作用域;

"<button type='button'  post-random-feed >Post review</button>"
.directive("postRandomFeed",['config',function(){
        return function(scope,element.attrs){ 
                element.bind("click", function(){
                    scope.name ="henry";
                     console.log(element);
                });

    }
}]);

我的问题是,我想定义一个独立的范围,并返回一个对象,而不是指令中的函数。这是我的代码

"<button type='button'  post-random-feed >Post review</button>"
.directive("postRandomFeed",['config',function(){
        return { 
            restrict :"A",
            scope : {
                    },
            irony : function(element, attrs)
            {   
                element.bind("click", function(){
                     console.log(element);
                });

            }
    };
}]);

我如何调用讽刺函数,使元素注册点击事件?如果有任何错误,请纠正我。谢谢

您可以向控制器注册回调:

html:

<button type='button'  post-random-feed on-irony="onControllerFn">Post review</button>

指令:

.directive("postRandomFeed",['config',function(){
        return { 
            restrict :"A",
            scope : {},
            link : function(scope, element, attrs) {   
                $timeout(function () {
                   scope.$emit(attr.onIrony);
                });
            });
        }
    };
}]);

在控制器中,您可以执行以下操作:

$scope.$on('onControllerFn', function(event) {
    // your code here
});