javascript Angular ng-click,ng-submit,ng-blur,ng-focus

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Angular ng-click,ng-submit,ng-blur,ng-focus相关的知识,希望对你有一定的参考价值。

/ 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...)

以上是关于javascript Angular ng-click,ng-submit,ng-blur,ng-focus的主要内容,如果未能解决你的问题,请参考以下文章

错误,使用 ng-cli 运行 ng serve 时编译失败

ng-cli新建项目

Angular2 EXCEPTION 没有字符串的提供者

Angular-cling 服务 livereload 不工作

Angular 2 中的 bundle.js.gz 文件是啥?

如何编写可重用的组件/模块?