Angularjs范围更新问题

时间:2013-05-14 13:41:01

标签: javascript angularjs angularjs-scope

我是angularjs的新手。面对如下问题 我的标记就像:

<div class="data-list">
    <ul ng-repeat="client in clients | orderBy:orderProp | filter:query">
        <li><a ng-click="update(client)"  data={{client.id}} href="#">{{client.name}}</a></li>
    </ul>
</div>
<div class="clientId">
    {{clientId}}
</div>

我的控制器就像:

function ClientListCtrl($scope, $http) {
    $http.get('/dummy-data/clients.json', {
        cache: false
    }).success(function (data) {
        $scope.clients = data.clients;
    });

    $scope.activeClient = {};
    $scope.update = function (selectedClient) {
        $scope.activeClient = angular.copy(selectedClient);
        console.log($scope.activeClient);
    }

    console.log("after click");
    console.log($scope.activeClient);
    // for sorting list 
    $scope.orderProp = '-numberOfUsers';
}

我希望当用户点击“客户端名称”时,{{clientId}}会更新,但范围会自动更新。并返回{}(空白对象)。

点击clientName后我如何获得{{clientId}}?

提前致谢。

2 个答案:

答案 0 :(得分:0)

您的控制器没有clientId之类的任何属性,而您ng-repeat的范围仅限于<ul>标记。

更改

<div class="clientId">
   {{clientID}}
</div>

<div class="clientId">
   {{activeClient}}
</div>

答案 1 :(得分:0)

您必须将{{clientId}}替换为{{activeClient.id}}

我根据你的代码做了一个简单的例子。

<强> HTML

<div ng-app="myApp">
    <div ng-controller="ClientListCtrl">
        <ul ng-repeat="client in clients">
            <li><a ng-click="update(client)" href="#">{{client.name}}</a></li>
        </ul>
        <div class="clientId"><br/>
            Client id: {{activeClient.id}}
        </div>
    </div>
</div> 

<强>的JavaScript

var myApp = angular.module('myApp',[]);

function ClientListCtrl($scope, $http) {
    $scope.clients = [
        {"id":1, "name": "client1"},
        {"id":2, "name": "client2"},
        {"id":3, "name": "client3"},
        {"id":4, "name": "client4"},
        {"id":5, "name": "client5"},
        {"id":6, "name": "client6"}
    ];

    $scope.activeClient = {};
    $scope.update = function(selectedClient) {
        $scope.activeClient = angular.copy(selectedClient);
    }
}

请参阅this jsfiddle