我不能决定在下面的情况下使用哪种方法。点击按钮时我正在尝试提醒。我可以用2种方法做到这一点。哪个是最好的做法,请告诉我为什么?
方法1
<div ng-app="app">
<button alert>directive</button>
</div>
var app = angular.module('app', ['ngRoute']);
app
.directive('alert', function(){
return {
link: function(scope, element, attr) {
element.on('click', function(){
alert('clicked');
})
}
}
})
方法2
<div ng-app="app" ng-controller="MainCtrl">
<button ng-click="go()">ng-click</button>
</div>
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.go = function() {
alert('clicked');
}
}]);
谢谢,
乳山
让我用例子向你解释一下。
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
正如您在示例中看到的那样 show-alert="[MSG]"
与直接使用相比,能够减少代码复制 $scope.showAlert
在每个控制器中。所以在这种情况下,创建指令更好。
但是,如果是的话 $scope.showConsole
只使用过一次,我们不会在任何地方重复使用它。所以直接在控制器内部使用它很好。
即使。你也可以创建指令 showConsole
功能,如果您将来感觉它也将在其他地方使用。它完全没问题。这个决定完全取决于你拥有的用例。
如果所有元素都必须在click事件上运行相同的函数,那么将其作为指令是一个好主意。否则使用ngClick。创建一个指令然后传递一个单击处理函数就是重新实现同样的事情。