AngularJS - 将函数传递给指令 [英] AngularJS - pass function to directive

查看:25
本文介绍了AngularJS - 将函数传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 angularJS 示例

<test color1="color1" updateFn="updateFn()"></test>

<脚本>angular.module('dr', []).controller("testCtrl", function($scope) {$scope.color1 = "颜色";$scope.updateFn = function() {警报('123');}}).directive('test', function() {返回 {限制:'E',范围:{颜色1:'=',updateFn: '&'},模板:<button ng-click='updateFn()'>点击</button>",替换:真的,链接:函数(范围,榆树,属性){}}});</html>

我希望当我点击按钮时,会出现警告框,但什么都不显示.

有人可以帮我吗?

解决方案

要从隔离作用域指令内部调用父作用域中的控制器函数,请在 HTML 中使用 dash-separated 属性名称,如OP说.

此外,如果您想向函数发送参数,请通过传递对象来调用该函数:

<test color1="color1" update-fn="updateFn(msg)"></test>

JS

var app = angular.module('dr', []);app.controller("testCtrl", function($scope) {$scope.color1 = "颜色";$scope.updateFn = 函数(味精){警报(味精);}});app.directive('test', function() {返回 {限制:'E',范围: {颜色 1: '=',updateFn: '&'},//调用时传递对象模板:<button ng-click='updateFn({msg : \"Hello World!\"})'>点击",替换:真的,链接:函数(范围,榆树,属性){}}});

小提琴

I have a example angularJS

<div ng-controller="testCtrl">

<test color1="color1" updateFn="updateFn()"></test>
</div>
 <script>
  angular.module('dr', [])
.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function() {
        alert('123');
    }
})
.directive('test', function() {
    return {
        restrict: 'E',
        scope: {color1: '=',
                updateFn: '&'},
        template: "<button ng-click='updateFn()'>Click</button>",
        replace: true,
        link: function(scope, elm, attrs) { 
        }
    }
});

</script>
</body>

</html>

I want when I click button, the alert box will appear, but nothing show.

Can anyone help me?

解决方案

To call a controller function in parent scope from inside an isolate scope directive, use dash-separated attribute names in the HTML like the OP said.

Also if you want to send a parameter to your function, call the function by passing an object:

<test color1="color1" update-fn="updateFn(msg)"></test>

JS

var app = angular.module('dr', []);

app.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function(msg) {        
        alert(msg);
    }
});

app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            color1: '=',
            updateFn: '&'
        },
        // object is passed while making the call
        template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
            Click</button>",
        replace: true,        
        link: function(scope, elm, attrs) {             
        }
    }
});

Fiddle

这篇关于AngularJS - 将函数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆