2013-10-04 32 views
0

我有一個複雜的模型結構(詳細內容如下),每次我想使用ng-model時,我都必須訪問如下所示的確切屬性:user.communications.inGame.selectedAngularJs從模型創建示波器

我希望能夠能範圍的區域,並且能夠使用內selected沒有所有的前綴(簡單地寫selected),就像我能與ng-repeat

ng-repeat不適合這裏,因爲每個通信都有不同的屬性,我不想在它裏面有一個巨大的ng-switch

數據結構

$scope.user.communications = { 
      inGame: { 
       name: 'inGame', 
       selected: true, 
       image: 'assets/img/communication/ingame.png' 
      }, 
      teamspeak: { 
       name: 'teamspeak', 
       selected: true, 
       image: 'assets/img/communication/ts.png', 
       serverAddress: '', 
       port: '', 
       nickname: '', 
       password: '', 
       channel: '', 
       channelPassword: '', 
       autoBookmarkAdd: '' 
      }, 
      skype: { 
       id: 3, 
       name: 'skype', 
       selected: true, 
       image: 'assets/img/communication/skype.png', 
       username: '' 
      }, 
      ventrilo: { 
       name: 'ventrilo', 
       selected: true, 
       image: 'assets/img/communication/ventrilo.png', 
       serverName: '', 
       port: '', 
       serverPassword: '', 
       channelName: '', 
       channelPassword: '' 
      } 
     }; 
+0

也許寫你自己的指令?類似'ng-with',然後做'ng-with =「user.communications.inGame」'不確定這是否適用於你,因爲這意味着模板需要在指令中。只是一個想法,但。 –

+0

我想獲得與ng-repeat相同的效果,只是不需要重複, 希望找到一個內置的解決方案,否則我可能會嘗試實現一個 –

+0

我認爲您至少需要一個前綴。 – kubuntu

回答

0

請檢查下面的HTML,你可以使用它像這樣

<div ng-app> 
    <h2>Todo</h2> 
    <div ng-controller="TodoCtrl">  
    <ul class="unstyled"> 
     <li ng-repeat="todo in user.communications"> 
     {{todo.selected}} 
     </li> 
    </ul>  
</div> 
    </div> 

和控制器

function TodoCtrl($scope) { 
$scope.user={}; 
$scope.user.communications = { 
     inGame: { 
      name: 'inGame', 
      selected: true, 
      image: 'assets/img/communication/ingame.png' 
     }, 
     teamspeak: { 
      name: 'teamspeak', 
      selected: true, 
      image: 'assets/img/communication/ts.png', 
      serverAddress: '', 
      port: '', 
      nickname: '', 
      password: '', 
      channel: '', 
      channelPassword: '', 
      autoBookmarkAdd: '' 
     }, 
     skype: { 
      id: 3, 
      name: 'skype', 
      selected: true, 
      image: 'assets/img/communication/skype.png', 
      username: '' 
     }, 
     ventrilo: { 
      name: 'ventrilo', 
      selected: true, 
      image: 'assets/img/communication/ventrilo.png', 
      serverName: '', 
      port: '', 
      serverPassword: '', 
      channelName: '', 
      channelPassword: '' 
     } 
    }; 

}

東西

請參考:http://jsfiddle.net/U3pVM/1505/

+0

謝謝,但我已經提到ng-repeat在這裏不適合,因爲每個通信都有不同的屬性,我希望能夠訪問其他屬性,而不使用ng-switch –

0

如果要動態地創建範圍,而在$scope.user.communications分別選擇每個項目,你可以簡單地使用ng-init。但是,它至少需要一個前綴

<div ng-model="one" ng-init="one=user.communications.inGame"> 
     {{ one.selected }} 
    </div> 
    ...