Let me explain it to you using example.
HTML
<div ng-app="myapp">
<div ng-controller="MyCtrl1">
<button ng-click="showAlert('hello')">Fist</button>
<button ng-click="showConsole('hello')">for Fist one only</button>
<button show-alert="first using directive">Fist with directive</button>
</div>
<div ng-controller="MyCtrl2">
<button ng-click="showAlert('hello second')">Second</button>
<button show-alert="first using directive">Second With directive</button>
</div>
<div ng-controller="MyCtrl3">
<button ng-click="showAlert('hello third')">Third</button>
<button show-alert="third using directive">third with directive</button>
</div>
</div>
JS
var myApp = angular.module('myapp',[]);
myApp
.controller('MyCtrl1', function ($scope) {
$scope.showAlert = function (msg) {
alert(msg);
};
$scope.showConsole = function (msg) {
console.log(msg);
};
})
.controller('MyCtrl2', function ($scope) {
$scope.showAlert = function (msg) {
alert(msg);
};
})
.controller('MyCtrl3', function ($scope) {
$scope.showAlert = function (msg) {
alert(msg);
};
})
.directive('showAlert', function(){
return{
restrict: 'A',
link: function(scope, ele, attr){
var eventName = attr.evetName || 'click';
var mas = attr.showAlert || 'just alert';
ele.on(eventName, function(){
alert(mas);
});
}
};
});
JsFiddleLink
As you can see in the example show-alert="[MSG]"
was able to reduce code replication compared to directly using $scope.showAlert
in each controller. so in this case creating directive was better.
But, in case of $scope.showConsole
was used only once, we are not reusing it anywhere. so its fine to use it directly inside controller.
Even though. you can also create directive for showConsole
functionality, if you feel like in future it will be used somewhere else also. its totally fine. this decisions totally depends on the what use-case you have.