AngularJS 控制代码详解

来源:luqidong 发布时间:2013-12-12 19:59:41 点击数:
  1. <!doctype html>
  2. <html ng-app> //添加对整个html的控制权
  3. <head>
  4. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>//加载angular
  5. <script src="todo.js"></script>//加载控制代码
  6. <link rel="stylesheet" href="todo.css">
  7. </head>
  8. <body>
  9. <h2>Todo</h2>
  10. <div ng-controller="TodoCtrl">//用TodCtrl控制这个层里面的内容
  11. <span>{{remaining()}} of {{todos.length}} remaining</span>//remaining是返回的变量
  12. [ <a href="" ng-click="archive()">archive</a> ]//单击的时候触发的方法
  13. <ul class="unstyled">
  14. <li ng-repeat="todo in todos">//让li重复填充
  15. <input type="checkbox" ng-model="todo.done">//要控制的checkbox
  16. <span class="done-{{todo.done}}">{{todo.text}}</span>//todo.done是返回的变量
  17. </li>
  18. </ul>
  19. <form ng-submit="addTodo()">//发送请求触发的方法
  20. <input type="text" ng-model="todoText" size="30"
  21. placeholder="add new todo here">
  22. <input class="btn-primary" type="submit" value="add">
  23. </form>
  24. </div>
  25. </body>
  26. </html>

 

todo.js部分代码

 

  1. function TodoCtrl($scope) {//TodoCtrl方法
  2. $scope.todos = [ //todos里面的元素值
  3. {text:'learn angular', done:true},
  4. {text:'build an angular app', done:false}];
  5.  
  6. $scope.addTodo = function() { //添加方法
  7. $scope.todos.push({text:$scope.todoText, done:false});
  8. $scope.todoText = '';
  9. };
  10.  
  11. $scope.remaining = function() { //判断checkbox选中的个数
  12. var count = 0;
  13. angular.forEach($scope.todos, function(todo) {
  14. count += todo.done ? 0 : 1;
  15. });
  16. return count;
  17. };
  18.  
  19. $scope.archive = function() {
  20. var oldTodos = $scope.todos;
  21. $scope.todos = [];
  22. angular.forEach(oldTodos, function(todo) { //循环判断执行
  23. if (!todo.done) $scope.todos.push(todo);
  24. });
  25. };
  26. }