Reputation: 1065
I'm learning AngularJS and am currently at this stage of it's tutorial. Full code available here on Github.
There's a component which has a controller with the following function:
self.setImage = function setImage(imageUrl) {
self.mainImageUrl = imageUrl;
};
which is really a method used in the Click event-handler for a img element:
<img ng-src="{{$ctrl.mainImageUrl}}" class="phone" />
...
<ul class="phone-thumbs">
<li ng-repeat="img in $ctrl.phone.images">
<img ng-src="{{img}}" ng-click="$ctrl.setImage(img)" />
</li>
</ul>
...
So what are the advantages to handling the event as above as opposed to:
<img ng-src="{{img}}" ng-click="$ctrl.mainImageUrl = img" />
? Does it have to do with keeping logic-handling out of the View? Any other considerations?
Upvotes: 0
Views: 44
Reputation: 16420
Yes basically, it's just for separation of concerns.
This is somewhat of an edge case situation as the code you need to execute is just one line. In this case it really is just a matter of opinion, some people prefer in the HTML some people don't.
Obviously if you write the Javascript code in the .js file you get intellisense and syntax highlighting and stuff like that, so easier to spot errors. + Your code can be linted. :-)
Also I'd recommend learning Angular 2 instead of 1. Angular 1 is redundant now.
Upvotes: 2
Reputation: 1102
In general the HTML in Angular is considered the "View" or the "Template". So there are at least two principles at work here:
In an MVC approach you want your Views to be "dumb". Basically, this is a crude way of saying don't put logic into your Views.
From a web development stand point, the template is the declarative part. So, your HTML should be declarative and not functional.
Finally, another reason is that keeping functional code in the controller increases the readability of your code. Other developers know to look for logic in the controller and don't need to hunt in the View when there is a bug in the logic.
All that being said, I do break those rules from time to time for convenience.
Upvotes: 1