如何根据与MVC angularJs值设置选择复选框在复选框列表

问题描述 投票:2回答:1

我想设置为喜欢在复选框列表“写作”,“足球”如何做到这一点选择的一些爱好吗?我的代码如下,

角控制器

$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>
angularjs asp.net-mvc checkboxlist
1个回答
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);
    });
};

参考A工作液:

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>
© www.soinside.com 2019 - 2024. All rights reserved.