dnc*_*253 13 angularjs angularjs-directive
我有一个像这样注册的控制器:
myModule.controller('MyController', function ($scope, ...some dependencies...)
{
....
Run Code Online (Sandbox Code Playgroud)
ng-controller="MyController"在HTML中使用它一切正常,但现在我想使用这个控制器作为我的指令的控制器.有点像这样:
otherModule.directive('myDirective', function() {
return {
restrict: 'A',
replace: true,
controller: ??????????,
scope: {
foo: '=',
blah: '=',
},
template: '....'
}
});
Run Code Online (Sandbox Code Playgroud)
我累了只是把MyController它错误地说"MyController没有定义".我敢肯定,如果我只是放入MyController全局命名空间,它会工作正常,但我不想在全局命名空间中有任何东西.如果它有所不同,myModule则定义为依赖项otherModule.我怎样才能获得对该控制器的引用以供我的指令使用?
正如所建议的那样,我试过$controller('MyController'),但现在我收到以下错误:
Error: Unknown provider: $scopeProvider <- $scope <- myDirectiveDirective
at Error (<anonymous>)
at http://localhost/resources/angular.js?_=1360613988651:2627:15
at Object.getService [as get] (http://localhost/resources/angular.js?_=1360613988651:2755:39)
at http://localhost/resources/angular.js?_=1360613988651:2632:45
at getService (http://localhost/resources/angular.js?_=1360613988651:2755:39)
at invoke (http://localhost/resources/angular.js?_=1360613988651:2773:13)
at Object.instantiate (http://localhost/resources/angular.js?_=1360613988651:2805:23)
at http://localhost/resources/angular.js?_=1360613988651:4621:24
at otherModule.directive.restrict (http://localhost/resources/app.js?_=1360613988824:862:15)
at Object.invoke (http://localhost/resources/angular.js?_=1360613988651:2786:25)
Run Code Online (Sandbox Code Playgroud)
我不知道该怎么做这个错误.还有更多需要使这项工作?
Rya*_*ill 25
看来你可以使用:
controller: 'MyController'
Run Code Online (Sandbox Code Playgroud)
如果控制器与指令位于同一模块中,或者由带有指令的模块组成的更高级别模块.
当我尝试将两个不同的模块组成一个app模块(一个用于控制器,一个用于指令)时,这不起作用.
Ben*_*esh 10
你已经接受的答案是有效的,几乎在所有情况下都应该选择 ......
为了完整起见:以下是如何使用其他模块的控制器
(PS:不要这样做.哈哈:P)
var app = angular.module('myApp', ['myDirectives']);
app.controller('AppCtrl1', function($scope) {
$scope.foo = 'bar';
});
var directives = angular.module('myDirectives', []);
directives.directive('test', function($controller) {
return {
template: '<h1>{{foo}}</h1>',
link: function(scope, elem, attrs) {
var controller = $controller('AppCtrl1', { $scope: scope });
console.log($scope.foo); //bar
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15805 次 |
| 最近记录: |