angularjs - Is passing a method as a string param to a directive not a bad thing? -
while discovering directives bumped on following:
<div ng-app="twitterapp"> <div ng-controller="appctrl"> <div enter>roll on load more tweets</div> </div> </div> var app = angular.module('twitterapp', []); app.controller("appctrl", function ($scope) { $scope.loadmoretweets = function () { alert("loading tweets!"); } }) app.directive("enter", function () { return function (scope, element, attrs) { element.bind("mouseenter", function () { scope.loadmoretweets(); }) } })
they say: "it better practice decouple loadmoretweets() method entirely passing directive string parameter in view, , retrieving attrs parameter in directive."
so becomes:
<div ng-app="twitterapp"> <div ng-controller="appctrl"> div enter="loadmoretweets()">roll on load more tweets</div> </div> </div> app.directive("enter", function () { return function (scope, element, attrs) { element.bind("mouseenter", function () { scope.$apply(attrs.enter); }) } })
but not going to:
**<div onclick="loadmoretweets()">roll on load more tweets</div>**
this confuses me, way javascript gets mixed again html. , aren't trying avoid that? use addeventlistener() , attachevent() these day's or see wrong.
here's 2 cents.
it's not we're trying remove script calls html it's don't want depend on html script work. way html can replaced , know plumbing (angularjs in case) still work. don't want reference angular side of wall (controllers, services) requires knowledge of dom (directives aside).
it creates clear separation of business logic (which can tested) , views (which pretty require human testing... until ai gets better).
there cases such click event there no avoiding having view have knowledge of underlying script, if 1 uses other connected. nice thing on angular side need keep interface same , can change actual implementation without messing view (it's interface , being able replace dependencies).
basically writing directive uses parameter potentially extend it's functionality call arbitrary functions instead of tying doing 1 specific task avoid need duplicate , tweak code (don't repeat yourself, dry).
long , short of de-coupling important knowledge of interface between parts work each other necessary. advantage of avoiding code repetition (therefore lots of places update if there's problems/tweaks) out-weighs desire keep knowledge of underlying structure hidden view.
keep in mind addeventlistener/attachevent still what's happening here, see element.bind call, still allow multiple event handlers.
Comments
Post a Comment