这里有新鲜出炉的 AngularJS 教程,程序狗速度看过来!
AngularJS 诞生于 Google 是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入,等等。
本篇文章主要介绍了深究 AngularJS——ng-checked(回写:带真实案例代码),具有一定的参考价值,感兴趣的小伙伴们可以参考一下
1. 需求
在添加页面实现一个 checkbox 的选择,然后在详情页面展示时,会自动选上之前被选中的。
2. 添加页面
看官最好将这个代码复制过去看看效果。
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
- </head>
- <body>
- <div ng-app="myApp" ng-controller="myCtrl" >
- 选择
- <div ng-repeat="item in list">
- <input type="checkbox" name="tagName" value="item.id" ng-click="select(item.id,$event)"> {{item.shortName}}
- </div>
- 结果:{{result}}
- </div>
- <script>
- var app = angular.module('myApp', []);
- app.controller('myCtrl', function($scope) {
- //创建checkbox用的
- $scope.list=[{"id":1,"shortName":"张三"},{"id":2,"shortName":"李四"},{"id":3,"shortName":"王二"}];
- //存储已选
- $scope.result = [];
- //触发事件
- $scope.select = function(id,event){
- console.log(event)//打印看看这是什么,有利于理解
- console.log(action)
- var action = event.target;
- if(action.checked){//选中,就添加
- if($scope.result.indexOf(id) == -1){//不存在就添加
- $scope.result.push(id);
- }
- }else{//去除就删除result里
- var idx = $scope.result.indexOf(id);
- if( idx != -1){//不存在就添加
- $scope.result.splice(idx,1);
- }
- }
- };
- });
- </script>
- </body>
- </html>
3. 详情展示
- //假设添加页面的结果是:$scope.result = [3,2];
- < !DOCTYPE html > <html > <head > <meta charset = "utf-8" > <script src = "http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js" > </script>
- </head > <body >
- <div ng - app = "myApp"ng - controller = "myCtrl" > 回写时设置不可选,即设ng - disabled = "true" < div ng - repeat = "item in list" > <input type = "checkbox"name = "tagName"ng - checked = "isSelected(item.id)"value = "item.id"ng - disabled = "true" > {
- {
- item.shortName
- }
- } < /div>
- 结果:{{result}}
- </div >
- <script >
- var app = angular.module('myApp', []);
- app.controller('myCtrl',
- function($scope) {
- //创建checkbox用的
- $scope.list = [{
- "id": 1,
- "shortName": "张三"
- },
- {
- "id": 2,
- "shortName": "李四"
- },
- {
- "id": 3,
- "shortName": "王二"
- }];
- //在添加页面得到的结果
- //你会发现,顺序也不会影响结果
- $scope.result = [3, 2];
- //被选中条件:ng-checked的结果为true
- $scope.isSelected = function(id) {
- return $scope.result.indexOf(id) != -1;
- //只要返回的结果为true,则对应的checkbox就会被选中,
- //所以我的思路是看存添加页面的结果里是否含有当前id即value值,
- //有就返回的true,没有就返回false
- };
- }); < /script>
- </body > </html>/
来源: http://www.phperz.com/article/17/0813/338695.html