如何根据MVC

时间:2017-05-27 08:07:17

标签: angularjs asp.net-mvc checkboxlist

我想在复选框列表中选择“写作”,“足球”等几个爱好如何做到这一点? 我的代码如下,

角度控制器

$scope.Hobbies = [];
$scope.Hobbies.push('Cricket');
$scope.Hobbies.push('Reading');
$scope.Hobbies.push('Writing');
$scope.Hobbies.push('Sleeping');
$scope.Hobbies.push('Running');
$scope.Hobbies.push('Football');
$scope.Hobbies.push('Programming');

$scope.selected = {};    
$scope.GetSelected = function () {        
    console.log('selected arry....');       
    $.each($scope.selected, function (value,checked) {
        console.log(value + '-' + checked);
    });
};

 $scope.SetSelected = function () {        
   //???
};

我的.cshtml代码

 <div><b>Hobbies</b>
                        <label ng-repeat="hobbie in Hobbies">                                
                            <input type="checkbox"
                                   checklist-model="Hobbies"
                                   ng-model="selected[hobbie]"                                      
                                   checklist-value="{{hobbie}}">{{hobbie}}                               
                        </label>
                    </div>
<a href="javascript:;" data-ng-click="SetSelected();">Set Selected</a>

1 个答案:

答案 0 :(得分:2)

您可以定义类似的列表。

$scope.Hobbies = [
     {name: 'Cricket', checked: true}, 
     {name: 'Reading', checked: false},
     {name: 'Writing'}
   ];

然后在你的视图中将其绑定:

<label ng-repeat="hobbie in Hobbies">                                
  <input type="checkbox"  ng-model="hobbie.checked">{{hobbie.name}}
</label>

要获得选定的爱好

$scope.GetSelected = function () {        
    $scope.Hobbies.forEach(function (hobbie) {
        console.log(hobbie.name,  hobbie.checked);
    });
};

供参考的工作解决方案:

angular.module('myApp',[])
.controller('Controller', function($scope) {
   $scope.Hobbies = [
     {name: 'Cricket', checked: true}, 
     {name: 'Reading', checked: false},
     {name: 'Writing'}
   ];
   
$scope.GetSelected = function () {        
    $scope.Hobbies.forEach(function (hobbie) {
        console.log(hobbie.name,  hobbie.checked);
    });
};

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-cloak ng-controller="Controller">
  <div><b>Hobbies</b>
    <label ng-repeat="hobbie in Hobbies">                                
                            <input type="checkbox"
                                   ng-model="hobbie.checked">{{hobbie.name}}                               
                        </label>
  </div>
  <a href="javascript:;" data-ng-click="GetSelected();">Get Selected</a>
</body>