0

我有需要从 json 数据更新的 html 结构。我的 Json 数据在控制器中。我需要为 ng-click 事件编写一个表达式,该表达式将读取 json 数据并将其放入 html 中的相应 div 中。但我不知道如何实现这一点。

以下是我到目前为止所拥有的。

<body data-ng-app>
    <div class="container" data-ng-controller="UpdateDataCtrl">
        <div class="inner1"></div>
        <div class="inner2"></div>
    </div>
    <a href="javascript:void(0)" ng-click="not sure how to get json here">UPdate Controllers</a>
</body>


function UpdateDataCtrl($scope) {
        $scope.data = [
            {
                "USA":"Eglish",
                "Pop":"232423432432"
            },
            {
                "France":"French",
                "Pop":"1212323432"
            },
            {
                "Spain":"Spainish",
                "Pop":"3432432"
            }
        ]
    }

每次单击时,2 Div 都应该从 json 更新。第一个 div 应该有 USA---English Pop---2342234232 然后在下一次单击时 div 应该有来自法国的数据,依此类推。

http://jsfiddle.net/MBFpD/1/

谢谢

4

2 回答 2

2

It appears that you are unclear on the concept of AngularjS. You don't want to update the DIVs. You want to reference your model and then change the data in your model.

For example you can write the div like this:

<div class="inner1">Population: {{data[dataindex].Pop}}</div>

Then in the Controller you initialize the dataindex to 0, so that this will output the population from the first entry in the array:

$scope.dataindex = 0;

The click function (you must have the link with the ng:click inside the block governed by the Controller!) could then just increase the dataindex by one and by using modulo restart at 0 again when the end of the array was reached.

$scope.click = function() {
  $scope.dataindex = ($scope.dataindex+1) % $scope.data.length;

Here is an updated and modified jsfiddle of your example which will show everything in action: http://jsfiddle.net/MBFpD/2/

于 2013-09-26T19:42:34.637 回答
0

当您单击链接时,将您的数据绑定到您的范围:

$scope.update = function() {
  $scope.data = data; //your array defined locally to the scope
};

ng-repeat您的数据绑定到范围;如果数组的大小 > 0,则显示容器。

用于{{index}}获取循环内的迭代变量。

最重要的是,将您的ng-controller声明移到顶部以将您的ng-repeat和您的ng-click; 否则,AngularJS 无法猜测您想要实现的目标。

http://jsfiddle.net/MBFpD/5/

于 2013-09-26T19:47:26.317 回答