2013-07-06 19 views
0

我試圖使用ng-repeat生成項目列表。不過,現在我已經輕鬆完成了這一步,但是我陷入了另一個問題。所以我試圖訪問和更新集合中的特定元素,但我真的無法弄清楚如何做到這一點。有誰知道如何做到這一點?或者可以指向正確的方向?如何使用angularJS訪問ng-repeat生成的集合中的特定元素

這裏有一個小提琴樣本:http://jsfiddle.net/VNLPY/(沒有做太多真的)

<body ng-app> 
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]"> 
I have {{friends.length}} friends. They are: 
<ul> 
<li ng-repeat="friend in friends"> 
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. 
</li> 
</ul> 
</div> 
</body> 

一件事,可以說我有數據正從一個JSON文件拉動。現在,我如何訪問集合中每行的每個值,以及如何更新JSON對象中的特定行。界面是否會與更新後的JSON保持同步?

由於

回答

1

This fiddle具有通過表達在ng-click以及ng-click遞增的特定朋友的年齡調用以簡單的控制裝置的功能的範圍的一個例子。

<a href="" ng-click="friend.age = friend.age + 1">Age + 1</a> 
    <a href="" ng-click="decrementAge(friend)">Age - 1</a> 

與控制器定義爲:

function TestController ($scope) { 
    $scope.decrementAge = function (friend) { 
     friend.age = friend.age - 1; 
    }; 
} 

角將處理保持模式和同步的圖。

+0

這就是我一直在尋找的!謝謝... – SolidSnake

1

您需要先正確構建應用程序。 Angular Seed是一個很好的起點。

一旦你有一個合適的控制器&視圖,你可以使用$ scope來實現你所要求的。

未測試

控制器

angular.module('myApp').controller('FriendsController', function($scope, $http) { 
    $scope.doSomethingWithAFriend = function(friend) { 
    // do something with your friend! 
    } 

    // $http is almost the same as jQuery.ajax except all the methods 
    // return promises based on the $q (q.js) spec. 
    $http.get('/api/friends').then(function(resp) { 
    $scope.friends = resp.data; 
    }, function(err) { 
    console.log(err); 
    }); 
}); 

查看

<li ng-repeat="friend in friends"> 
    [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. 
    <a href="" ng-click="doSomethingWithAFriend(friend)">Do Something</a> 
</li> 

編輯:我應該提到適當的地方做API CAL ls(或任何AJAX /數據操作)位於Services。我只是把它作爲一個簡單的例子放在控制器中。

+0

感謝您的解決方案。我明白了:) – SolidSnake

相關問題