AngularJs从模型创建范围

时间:2013-10-04 13:58:50

标签: angularjs angularjs-scope

我有一个复杂的模型结构(详见下文),每次我想使用ng-model时,我都必须访问以下精确属性:user.communications.inGame.selected

我希望能够确定某个区域的范围,并且能够使用内部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: ''
            }
        };

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

如果您想在$scope.user.communications单独选择每个项目时动态创建范围,则只需使用ng-init即可。但是,它至少需要一个前缀

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