angularJS:ng-repeat作用域及父作用域调用$parent

一、关于ng-repeat的作用域学习:

1、ng-repeat会在上一级作用域名中创建一个子 作用域。

2、此时如果需要在子作用域中调用父作用域的变量,则可以使用$parent.variableName来调用。

3、ng-repeat中调用和父作用域同名的变量,无$parent前缀则指的是调用的子作用域的变量,就像局部变量一样。

4、ng-repeat中的$index: element in elements  当前element在elements中的下标数。例如第一个element,则$index=0.

二、代码效果

三、详细代码

 1 <DOCTYPE html>
 2 <html ng-app="app">
 3 <head>
 4 <meta charset="utf-8"/>
 5 <title>ng-repeat</title>
 6 <script src="jquery-1.10.2.min.js"></script>
 7 <script src="angular.min.js"></script>
 8 </head>
 9 <body >
10 <h1>scope</h1>
11 <div ng-controller="ParentCtrl" >
12 ParentCtrl:<br/>
13 父scope的countrywaibu:{{countrywaibu}}<br/>
14 父scope的countries:<br/>{{countries|json}}
15 <ul>
16 <li ng-repeat="countrywaibu in countries">ng-repeat:<br/>
17 child 中调用父scope的$parent.countrywaibu :{{$parent.countrywaibu}}<br/>
18 child中与父scope同名的countrywaibu的countrywaibu.name:    <input type="text" ng-model="countrywaibu.name"></input>
19     <span>{{countrywaibu.name}}</span><br/>
20     <button ng-click="remove($index)" >移除countries中的当前元素</button>
21 </li>
22 </ul>
23 </div>
24 
25 <script type="text/javascript" chartset="utf-8">
26 // the controller
27 var app=angular.module('app',[]);
28 app.controller('ParentCtrl',function($scope){
29     $scope.countrywaibu="waibu";
30     $scope.population = 7000;
31     $scope.countries = [
32         {name: 'France', population: 63.1},
33         {name: 'United Kingdom', population: 61.8}
34     ];
35     $scope.remove = function(index) {
36         //删除index下标的某个元素
37         $scope.countries.splice(index, 1);
38         }
39 });
40 </script>
41 
42 </body>
43 </html>

 

posted @ 2014-12-13 21:55  testForever  阅读(9105)  评论(0编辑  收藏  举报