Ответ 1
Позвольте мне объяснить это вам, используя пример.
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);
});
}
};
});
Как вы можете видеть в примере show-alert="[MSG]"
удалось уменьшить репликацию кода по сравнению с непосредственным использованием $scope.showAlert
в каждом контроллере. поэтому в этом случае лучше создать директиву.
Но в случае $scope.showConsole
использовался только один раз, мы не используем его где-либо еще. поэтому его штраф, чтобы использовать его непосредственно внутри контроллера.
Хотя. вы также можете создать директиву для showConsole
функциональности, если вы чувствуете, что в будущем она будет использоваться и в другом месте. это совершенно нормально. эти решения полностью зависят от того, какой вариант использования у вас есть.