Javascript 自定义指令上的角度控制器
这是我的Javascript 自定义指令上的角度控制器,javascript,angularjs,Javascript,Angularjs,这是我的controllers.js文件 (function(ctx,angular){ 'use strict'; angular.module('app.controllers') .controller('SearchMasterController',['$scope',function($scope){ //My Code }]); })(window, angular); (function(ctx,angular){ f
controllers.js
文件
(function(ctx,angular){
'use strict';
angular.module('app.controllers')
.controller('SearchMasterController',['$scope',function($scope){
//My Code
}]);
})(window, angular);
(function(ctx,angular){
function ControllerFunction(){
//My Controller Code
}
var directiveConfig = {
restrict:'E',
templateUrl:'path/to/acco.html',
controller: ControllerFunction
}
angular.module('app.directives')
.directive('acco', function(){
return directiveConfig;
});
})(window, angular);
这是我的directions.js
文件
(function(ctx,angular){
'use strict';
angular.module('app.controllers')
.controller('SearchMasterController',['$scope',function($scope){
//My Code
}]);
})(window, angular);
(function(ctx,angular){
function ControllerFunction(){
//My Controller Code
}
var directiveConfig = {
restrict:'E',
templateUrl:'path/to/acco.html',
controller: ControllerFunction
}
angular.module('app.directives')
.directive('acco', function(){
return directiveConfig;
});
})(window, angular);
现在我的问题是,我可以将这个acco
指令用于不同的控制器吗。理想情况下,有没有办法让它正常工作
我试着
<acco>
<div ng-controller="SearchMasterController"></div>
</acco>
这似乎奏效了
可以使用吗
后一种选择在我看来很难看。是的,您可以为您的指令使用不同的控制器,但也有一些 当您想向其他指令公开API时,请使用控制器。否则请使用链接 您尝试使用控制器的方式没有多大意义
<!--here acco and ng-controller both are directives,
in your directive's 'ControllerFunction' and ng-controller's 'SearchMasterController'
has the same controll (scope) for 'acco' rendered html.
In that case your directive's controller overrite ng-controller functionality.
So leave 'ng-controller',
if you need any functionality in your directive
then pass those functionality using =,&,@-->
<acco ng-controller="SearchMasterController"></acco>
很高兴听到这种访问方式,我已经尝试过了
<acco>hi{{name1}}
<div ng-controller="SearchMasterController">{{name1}}</div>
</acco>
<acco ng-controller="SearchMasterController">{{name1}}</acco>
<script>
angular.module('myApp', [])
.controller('SearchMasterController', ['$scope', function ($scope) {
//My Code
console.log("search");
$scope.name1 = 'james';
}])
.directive('acco', function () {
return{
restrict: 'E',
templateUrl: 'acco.html',
controller: function($scope) {
//My Controller Code
console.log("cntrlr fn");
$scope.name1 = 'semaj';
}
};
});
</script>
意思是如果我们使用like
<acco>hi{{name1}}
<div ng-controller="SearchMasterController">{{name1}}</div>
</acco>
<acco ng-controller="SearchMasterController">{{name1}}</acco>
hi{{name1}
{{name1}
然后我们可以访问两个控制器,但当我们使用like时
<acco>hi{{name1}}
<div ng-controller="SearchMasterController">{{name1}}</div>
</acco>
<acco ng-controller="SearchMasterController">{{name1}}</acco>
{{name1}
我们无法访问SearchMasterController,它也未加载。请检查此项: