猿问

AngularJS-将函数传递给指令

我有一个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>

我想要当我单击按钮时,将出现警报框,但什么也没显示。


谁能帮我?


有只小跳蛙
浏览 606回答 3
3回答

达令说

要从隔离作用域指令内部在父作用域中调用控制器功能,请dash-separated在HTML中使用属性名称,如OP所述。另外,如果要向函数发送参数,请通过传递对象来调用函数:<test color1="color1" update-fn="updateFn(msg)"></test>JSvar app = angular.module('dr', []);app.controller("testCtrl", function($scope) {&nbsp; &nbsp; $scope.color1 = "color";&nbsp; &nbsp; $scope.updateFn = function(msg) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; alert(msg);&nbsp; &nbsp; }});app.directive('test', function() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; restrict: 'E',&nbsp; &nbsp; &nbsp; &nbsp; scope: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color1: '=',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; updateFn: '&'&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; // object is passed while making the call&nbsp; &nbsp; &nbsp; &nbsp; template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Click</button>",&nbsp; &nbsp; &nbsp; &nbsp; replace: true,&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; link: function(scope, elm, attrs) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }});

largeQ

在“测试”指令Html标记中,函数的属性名称不应为驼峰式,而应基于破折号。所以-代替:<test color1="color1" updateFn="updateFn()"></test>写:<test color1="color1" update-fn="updateFn()"></test>这是angular区分指令属性(例如update-fn函数)和函数之间差异的方法。
随时随地看视频慕课网APP

相关分类

AngularJS
我要回答