/ NG-CLICK, NG-SUBMIT, NG-BLUR, NG-FOCUS, NG-CHANGE
// Any event than you can think, Angular has its ng- equivalent
//(look for them: ngMouseover, ngMouseleave...)
// ng-click binds an element to a particular function in our controller
<li ng-repeat="movie in $ctrl.favorites">
<a href="" ng-click="movies.addToLikes(movie);">Like this movie</a>
//we are inside ng-repeat, we can pass the current movie to the function
</li>
...
<li ng-repeat="like in $ctrl.likesList">
{{like.title}} <a href="" ng-click="movies.unlike($index);">Unlike!</a>
//we're passing the index of the current element
</li>
//MoviesController.js
function MoviesController() {
this.likesList = [];
this.addToLikes = function(movie){
this.likesList.push(movie);
};
this.unlike = function(index){
this.likesList.splice(index, 1); //splice removes an element of an array based on its index.
//We want to delete 1 element forward
};
this.favorites = [{
//...
}];
}
// All the process 'data-driven': we add/remove items from an array,
// using basic array functionality,
// what makes our makes our UI very responsive.
// Angular also cleans the event listeners for us (for example when we remove a movie
// from the LikesList) to avoid memory leaks.
// ng-submit automatically uses event.preventDefault() to stop the form submission,
// so we can use ajax or whatever we want to do with the form data.
<form ng-submit="$ctrl.addMovie();">
<input type="text" ng-model="$ctrl.newTitle" placeholder="Title">
<input type="text" ng-model="$ctrl.newRelease" placeholder="Release year">
</form>
//
//MoviesController.js
function MoviesController() {
this.newTitle = '';
this.newRelease = '';
this.addMovie = function(){
this.movies.unshift({ //we use unshift instead of push to add the new element
//to the start of the array
title: this.newTitle,
year: this.newYear
});
};
...
}
// Note that indexes are updated as Angular manipulates the array
// (so the new element added is index 0 and the rest of the indexes are updated).
// ng-blur / ng-focus could be useful for validation:
// for example to check if the movie we are adding already exists in the database.
<input
type="text"
placeholder="Title"
ng-focus="movies.onFocus();"
ng-blur="movies.onBlur();"
ng-model="movies.newTitle">
// ng-change is useful in inputs to check *when* they change its value.
// For example for comunicating with the backend as the user writes,
// and make suggestions/autocomplete.
// (ampliar un ejemplo de esto...)