2013-08-16 120 views
0

所有我想要做的就是出現如下圖所示的主列表O」項目所選擇的項目。我之前做過這件事,但由於某種原因,這只是不行爲,我無法弄清楚我錯過了什麼。選定的項目將不會顯示

的HTML(下調只是相關部分):

<ul> 
    <li data-ng-repeat="user in users" ng-click="$parent.selectUser($index)" ng-model="$index"> 
     {{user.userName}} 
    </li> 
</ul> 

<p>Selected: {{selected.userName}}, #<b>{{$index}}</b></p> 

的JS:

(function (app) { 
    app.controller('UsersController', [ '$scope', function ($scope) { 
     $scope.selectUser = function ($index) { 
      $scope.selected = $index; 
      console.info('selected1=' + $index); 
     }; 
     $scope.selected = null; 
    }]); 
}); 

控制檯日誌顯示了選擇的指數,但沒有發生在html的最後一行 - 沒有selected.userName,沒有$ index。我嘗試了各種變化,沒有任何反應。我錯過了什麼?提前致謝!

(注:我不知道我使用的是NG-模式有正確的,要麼,但似乎是附帶與否,我可以得到所選擇的$索引中反映出來)

+1

。你不需要它,如果方法在父範圍上,它將在子範圍上可用。 – Chandermani

+0

我想NG-重複創建隔離/子範圍,我想保持選擇的任何編輯作爲父範圍則使那些將可在其他地方的一部分。 – kl02

回答

1

您正在嘗試使用$indexng-repeat這不會在外面工作,如$index只是ng-repeat上下文中使用。

既然您是設置

$ scope.selected = $ index;

你需要使用selected變量

我想你想要的是選擇上點擊用戶。這應該像這樣完成。

<ul> 
    <li data-ng-repeat="user in users" ng-click="selectUser(user,$index)" ng-model="$index"> 
     {{user.userName}} 
    </li> 
</ul> 

<p>Selected: {{selected.userName}}, #<b>{{index}}</b></p> 

爲什麼你使用`$ parent` selectUser你的控制器將有

$scope.selectUser = function (user,index) { 
      $scope.selected = user; 
      $scope.index=index; 
     }; 
+0

非常好,謝謝!一個注意:控制器的最後一行應該是$ scope.index = $ index - 當我沒有使用$時,我得到了一個'undefined'味精。添加$使它完全像我需要的那樣工作。好極了! – kl02

+0

取決於函數參數,我的fn參數使用'index'。 – Chandermani