为了账号安全,请及时绑定邮箱和手机立即绑定

AngularJS-将函数传递给指令

AngularJS-将函数传递给指令

有只小跳蛙 2019-10-08 10:48:50
我有一个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>我想要当我单击按钮时,将出现警报框,但什么也没显示。谁能帮我?
查看完整描述

3 回答

?
达令说

TA贡献1821条经验 获得超6个赞

要从隔离作用域指令内部在父作用域中调用控制器功能,请dash-separated在HTML中使用属性名称,如OP所述。


另外,如果要向函数发送参数,请通过传递对象来调用函数:


<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) {             

        }

    }

});


查看完整回答
反对 回复 2019-10-08
?
largeQ

TA贡献2039条经验 获得超7个赞

在“测试”指令Html标记中,函数的属性名称不应为驼峰式,而应基于破折号。


所以-代替:


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

写:


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

这是angular区分指令属性(例如update-fn函数)和函数之间差异的方法。


查看完整回答
反对 回复 2019-10-08
  • 3 回答
  • 0 关注
  • 568 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信