在Angularjs中,指令是个好东西,可以极大的提高代码的重用性,也可以使各个模块之间解耦,提高代码的可维护性。但是在实际开发中,仅仅用它来传递值是远远不够的,传递方法在很多情况下比传递值更加有效,下面我来介绍下如何往directiive中传递方法。
收先我们定义一个指令,用来执行controller中的一个方法
var app = angular.module('App'); app .directive("myDirective", [MyDirective]); function MyDirective() { return { restrict: 'E', bindToController: { // 将参数传入Controller的this变量中 msg: "=",//接收从controller中传入的参数 func: "&",//传入的方法,需要传入参数msg }, controller: [MyDirectiveCtrl], //指令中controller的名称 controllerAs: 'myDirectiveCtrl', //别名 templateUrl: "myDirective.view.html" } } function MyDirectiveCtrl(){//指令控制Controller啥都不用干 }指令的模板页面myDirective.view.html。注意:调用的时候是重点,要传入一个对象,key为传入方法的变量名称,value是真实值
<div>传入的msg为{{myDirectiveCtrl.msg}}</div> <button ng-click="myDirectiveCtrl.func({msg:myDirectiveCtrl.msg})">点击触发传入的方法</button>Controller中随便定义一个方法
var app = angular.module('App'); app .controller("MyController", [MyController]); function MyController(){ var vm = this; vm.msg = "传递到directive中的msg"; vm.callback = callback; function callback(msg){ alert(msg); } }Controlle的页面,注意,传入回调方法的参数(即”msg”),就是指令调用该方法,传入参数的key
<div ng-controller="MyController as myController"> <my-directive msg="myController.msg" func="myController.callback(msg)"></my-directive> </div>
本文介绍了AngularJS中如何在指令中传递和调用函数,强调了这种方法在提高代码重用性和解耦方面的优势。通过创建一个指令并在模板页面中调用控制器的方法,演示了将函数作为参数传递的过程,并指出在调用时需要传入包含函数的对象。

被折叠的 条评论
为什么被折叠?



