Since I began learning AngularJS I've seen different approaches for calling controller functions from a view.
Suppose we have a Todo list application in AngularJS where you can add and remove Todo list items:
function TodoListCtrl() {
var vm = this;
vm.addItem = addItem;
vm.removeItem = removeItem;
activate();
function activate() {
vm.list = [];
}
function addItem() {
vm.list.push(vm.newItem);
// reset the form
vm.newItem = null;
}
function removeItem(item) {
vm.list.splice(vm.list.indexOf(item, 1));
}
}
And our HTML:
<h3>Todo List</h3>
<ul>
<li ng-repeat="item in vm.list">
{{ item }} <a ng-click="vm.removeItem(item)">Remove</a>
</li>
</ul>
<h4>Add Item</h4>
<input type="text" ng-model="vm.newItem" /> <button ng-click="vm.addItem()">Add</button>
In this example the addItem function depends on vm.newItem being set in order to add the new list item. However, it could also be re-written as:
function addItem(item) {
vm.list.push(item);
// reset the form
vm.newItem = null;
}
With our HTML updated as so:
<button ng-click="vm.addItem(vm.newItem)">Add</button>
I can see that this makes the function easier to test since we're not dependent on the state of the controller but we don't avoid it completely since we're resetting vm.newItem after an item is added.
Are there any best practices for when we should pass parameters from our views and when we can just rely on the internal state of the controller?
ng-disabled="!vm.newItem"on the button as well, maybe wrap with anif (item) { }in the controller function.