我尝试“要求”一个父控制器(不是指令),但是AngularJS返回一个异常。代码是这样的:
app.controller("myController", function ($scole) { ... }); app.directive("myDirective", function ($q) { return { require: "^myController", template: "", link: function (scope, element, attrs, myCtrl) { ... } }; });
<div ng-controller="myController as myCtrl"> ... <div my-directive>...</div> ... </div>
错误:找不到指令’myDirective’所需的[$ compile:ctreq]控制器’myController’!
为什么? 也许,require属性必须引用 指令 的控制器?
require
谢谢
要求在另一个指令中使用其他指令控制器,请参考以下示例
var App = angular.module('myApp',[]); //one directive App.directive('oneDirective',function(){ return { restrict: 'E', controller:function($scope){ $scope.myName= function(){ console.log('myname'); } } } }); //two directive App.directive('twoDirective',function(){ return { require:'oneDirective' //one directive used, link : function(scope,ele,attrs,oneCtrl){ console.log(oneCtrl.myName()) } } })