我打算只关注指令控制器的使用。所以,pl回答了我提到的每个指令用法实例所提到的相同错误,在指令中提到的控制器部分中,angular会出现一次。
//module declaration
var app = angular.module('myApp',[]);
//controller declaration
app.controller('myCtrl',function($scope){
$scope.name = "Peter";
});
//app declaration
app.directive('myStudent',function(){
return{
template: "Hi! Dear!! {{name}}<br/>",
controller:function(scope, elem, attr){
console.log("controller");
}
}
});
&#13;
<body ng-app="myApp" ng-controller="myCtrl">
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>
&#13;
注意:
PS:我不理解一些外星天才的投票结果!请注意,只关注错误和使用指令控制器。我知道同样可以通过预链接,后链接或编译来完成。
答案 0 :(得分:5)
我认为它应该是链接功能而不是控制器。
//module declaration
var app = angular.module('myApp', []);
//controller declaration
app.controller('myCtrl', function($scope) {
$scope.name = "Peter";
});
//app declaration
app.directive('myStudent', function() {
return {
template: "Hi! Dear!! {{name}}<br/>",
link: function(scope, elem, attr) {
console.log("controller");
}
}
});
&#13;
<body ng-app="myApp" ng-controller="myCtrl">
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>
&#13;
最佳实践:当您希望将API公开给其他指令时,请使用控制器。否则使用链接。
Controller接受一个数组:
var app = angular.module('myApp', []);
//controller declaration
app.controller('myCtrl', function($scope) {
$scope.name = "Peter";
});
//app declaration
app.directive('myStudent', function() {
return {
template: "Hi! Dear!! {{name}}<br/>",
controller: [
function(scope, elem, attr) {
console.log("controller");
}
]
}
});
&#13;
<body ng-app="myApp" ng-controller="myCtrl">
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<my-student></my-student>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>
&#13;
如需进一步阅读,我建议angular documentation on directives