Reputation: 8240
I intend to focus on usage of Directive Controller only. So, pl answer around the same error as mentioned as I suppose for each instance of directive usage, angular would go once in controller section mentioned in Directive.
//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");
}
}
});
<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>
Note:
Kindly, throw light on error and on usage of directive controller only. I know same can be done by pre-link, post-link, or compile.
PS: I dont understand the vote-down from some extra-terrestrial Genius!
Upvotes: 2
Views: 49
Reputation: 5466
I think it should be link function instead of controller.
//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");
}
}
});
<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>
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.
Controller accepts an array:
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");
}
]
}
});
<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>
For further read I would suggest angular documentation on directives
Upvotes: 6