【问题标题】:How to call a function out of directive如何从指令中调用函数
【发布时间】:2016-10-27 12:01:09
【问题描述】:

在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 来编写它。但是按钮有点击功能:click1,click2,click3等等。如何在指令中调用函数 click1,click2...?

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

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

【问题讨论】:

  • 指令有什么scope 属性?另外,为什么只使用一种接受 "index" 参数的方法?

标签: angularjs angularjs-directive


【解决方案1】:

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

你的指令

(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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多