javascript - Angularjs - ng-click function vs directive -
i can't decide method use in following case. i'm trying alert when clicking on buttons. can using 2 methods. best practice , please tell me why?
method 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'); }) } } })
method 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'); } }]);
thank you, rushan
let me explain 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 1 only</button> <button show-alert="first using directive">fist directive</button> </div> <div ng-controller="myctrl2"> <button ng-click="showalert('hello second')">second</button> <button show-alert="first using directive">second directive</button> </div> <div ng-controller="myctrl3"> <button ng-click="showalert('hello third')">third</button> <button show-alert="third using directive">third 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); }); } }; });
as can see in example show-alert="[msg]"
able reduce code replication compared directly using $scope.showalert
in each controller. in case creating directive better.
but, in case of $scope.showconsole
used once, not reusing anywhere. fine use directly inside controller.
even though. can create directive showconsole
functionality, if feel in future used somewhere else also. totally fine. decisions totally depends on use-case have.
Comments
Post a Comment