As the name suggests, what is the difference? A controller is suppose to act as a constructor - to instantiate all the variables and/or make API calls.
A directive's controller also runs before the DOM is compiled, and so I am wondering if it could be used for the some context? In other words, are these two codes the same?
Say that I have this markup:
<div my-div ng-controller="DivController">
Here is the Javascript:
angular
.module('myApp')
.controller('DivController', function($scope) {
$scope.value = 'initialize';
})
.directive('myDiv', function() {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
// Now use $scope.value
}
}
});
// VS this code
angular
.module('myApp')
.directive('myDiv', function() {
return {
restrict: 'EA',
controller: function($scope) {
$scope.value = 'initialize';
},
link: function(scope, element, attrs) {
// Now use $scope.value
}
}
});
ng-controllercreates a new scope.