2013-05-14 139 views
1

我是angularjs的新手。面對一個問題,像下面 我的標記是這樣的: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}}將被更新,但範圍更新它自我。並返回{}(空白對象)。

如何在點擊客戶端名稱後獲得{{clientId}}?

在此先感謝。

回答

0

您的控制器沒有任何財產,如clientId,您的ng-repeat僅限於<ul>標籤。

變化

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

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

您有{{activeClient.id}}

更換{{clientId}}我會根據您的代碼,一個簡單的例子。

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

+0

嘿,感謝的jsfiddle,但在我的代碼它不是wroking。我的標記是像http://jsfiddle.net/YcP9S/ – arnold 2013-05-14 14:39:21

+0

看到http://jsfiddle.net/YcP9S/1/是你的標記(我只添加ng-app div)與我的js。它工作正常。檢查你的js或粘貼在jsfiddle看看 – pbaris 2013-05-14 14:44:02