1

在输入标签类型复选框中将 ng-models 与 ng-repeat 绑定时出现问题。我将首先附上我的代码,然后再详细解释。

应用程序/main.html:

<div ng-repeat="feature in features">
   <input type="checkbox" ng-model="features[$index].name">{{features[$index].name}}
</div>
<br></br>
  <div class="highlighter">
     <span ng-class="{emo:Emotions}">Manually</span> <span ng-class="{feel:Feelings}">create</span> the <span ng-class="{emo:Emotions}">entire</span>
  </div>

main.js

angular.module('webClientApp')
    .controller('MainCtrl', function ($scope,$http) {

       [...other variables...]

       $scope.features = [{'name':'Emotions'},{'name':'Feelings'}];

[...other parts of code]
});

我们还假设在 main.css 文件中分别引用了类.emo' and.feel' 以在用户勾选与该功能相关的框时突出显示目标词。

现在,当我一一列出所有输入时,应用程序可以正常工作,如下所示:

<input type="checkbox" ng-model="Emotions">Emotions
<input type="checkbox" ng-model="Feelings">Feelings

但我想将它包装成一个 ng-repeat 并列出控制器范围内的功能,因为我将考虑的功能会更多。当我在框上打勾时尝试上面的代码时,名称更改为“true”。

我已经阅读了很多关于如何将模型绑定到输入标签内的 ng-repeat 的内容,但没有一个解决方案适用于我的案例。有人可以帮帮我吗?

4

3 回答 3

0

您必须使用ng-checked而不是ng-model.

看看这个 jsfiddle

http://jsfiddle.net/fizerkhan/z5z9s/24/

ngModel并且ngChecked不打算一起使用。

ngChecked期待一个表达,所以说ng-checked="master". 如果表达式为真,则将在元素上设置特殊属性“checked”

您应该能够使用ngModel, 绑定到模型上的布尔属性。如果你想要别的东西,那么你要么需要使用 ngTrueValue 和 ngFalseValue(现在只支持字符串),要么编写自己的指令。

于 2014-02-20T16:46:04.713 回答
0

(我应该将此添加为评论,但我还没有足够的代表。)github上有一个与您的问题有关的问题:https ://github.com/angular/angular.js/issues/1404和caitp 的评论显示了一些解决方法:https ://github.com/angular/angular.js/issues/1404#issuecomment-30859987

您可以(也)在控制器中定义一个新的 javascript 对象并将元素映射到该对象。

在控制器中:$scope.awnsers = {};

在模板中:ng-model="awnsers[feature.name]"

我希望这有帮助

于 2014-02-20T16:08:01.037 回答
0

我从你的原始模型中改变了很多,但是......我确实得到了一些行为类似于你正在寻找的东西。

HTML

<div ng-app="webClientApp">
<div ng-controller="MainCtrl">
    <div ng-repeat="(feature,enabled) in features">
        <input type="checkbox" ng-model="features[feature]">{{feature}}</input>
    </div>
      <div class="highlighter">
         <span ng-class="{emo:features.Emotions}">Manually</span> <span ng-class="{feel:features.Feelings}">create</span> the <span ng-class="{emo:features.Emotions}">entire</span>
      </div>
    {{features}}<br>
    {{features.Emotions}}<br>
    {{features.Feelings}}
</div>

JS

var app = angular.module('webClientApp', []);
app.controller('MainCtrl', function($scope, $http) {
    $scope.features = {Emotions: true, Feelings: true};
});

这是小提琴:http: //jsfiddle.net/rodhartzell/8YrxQ/

希望这可以帮助。

于 2014-02-20T17:22:50.257 回答