如何从指令中调用函数

时间:2016-10-27 03:20:02

标签: angularjs angularjs-directive

在html中,我写道:

<div ng-controller="cxController">
   <my-dir test-data="testdata"></my-dir>
 </div>

在cxController中,我写道:

$scope.testdata={
  spanInfo:{},
  buttonInfo:{}
};
$scope.click1=function(){};
$scope.click2=function(){};
$scope.click3=function(){};

在指令中,有一些跨度和按钮。并且没有设置按钮编号,我需要使用ng-repeat来编写它。但该按钮具有单击功能:单击1,单击2,单击3,依此类推。如何调用函数click1,在指令中单击2 ...

告诉指令在buttonInfo中有一些像这样的函数吗?

$scope.testdata={
  spanInfo:{},
  buttonInfo:{
    {click:$scope.click1}
    {click:$scope.click2}
  }
};

1 个答案:

答案 0 :(得分:0)

这是一种方式,我习惯从指令调用控制器函数。 你能利用这个吗?

你的指令

(function() {
    'use strict'; 
    angular
        .module('app')
        .directive('myDir', myDir);

    myDir.$inject = [];

    function myDir() {
        return {
            restrict: 'AE',
            scope: { 
                onClick : '&' ,
            },
            template: '<div>'+
                        '<button ng-click="onClick()"></button'+
                     '</div>',
            link: function(scope, element, attrs) {

            }
        }
    }
})();

控制器

(function() {
    'use strict';

    angular
        .module('app')
        .controller('myController', myController);

    myController.$inject = [];

    function myController() {

        var vm = this;

        vm.callControllerFn = function(){
            alert("called")
        }

    }
})();

查看

<my-dir on-click="vmA.callControllerFn();"></my-dir>