在Angular.js中附加到模型的复选框

checkboxes that append to a model in Angular.js

本文关键字:模型 复选框 Angular js      更新时间:2023-09-26

我有一个模型,它将与许多其他模型相关。想象一个堆栈溢出问题,例如,它是一个与标记相关的问题。在POSTPUT:之前,最后一个Object可能如下所示

{
  id: 28329332,
  title: "checkboxes that append to a model in Angular.js",
  tags: [{
    id: 5678,
    name: "angularjs"
  }, {
    id: 890,
    name: "JavaScript"
  }]
}

到目前为止,我有以下控制器:

.controller('CreateQuestionCtrl',
    function($scope, $location, Question, Tag) {
      $scope.question = new Question();
      $scope.page = 1;
      $scope.getTags = function() {
        Tag.query({ page: $scope.page }, function(data) {
          $scope.tags = data;
        }, function(err) {
          // to do, error when they try to use a page that doesn't exist
        })
      };
      $scope.create = function() {
        $scope.question.$save(function(data) {
          $location.path("/question/" + data.id);
        });
      };
      $scope.$watch($scope.page, $scope.getTags);
    }
  )

所以我在页面上显示所有的标签,分页。我希望他们能够选择给定的标签,并将其附加到我的模型中,以便保存它。

如何创建一个复选框界面,使其使用选定的其他型号更新$scope.question


编辑:我想我可能是的一部分

<div class="checkbox" ng-repeat="tag in tags.objects">
  <label><input
    type="checkbox"
    ng-change="setTag(tag.id)"
    ng-model="tag"
  >&nbsp;{{ tag.name }}
</div>

然后在控制器上

$scope.setTag = function(id) {
  Tag.get({id: id}, function(data) {
    // don't know what now
  })
}

基本上,它需要一个指令来实现你的目标看看我为你写的plunker。正如您所看到的,在所选标记的列表中,每个标记的text属性都会显示出来,这意味着保留了对象结构。在您的情况下,您将绑定$scope.question.tags数组作为collection属性,并将$scope.tags中的每个标记作为element属性。

这里是绑定到同一模型的多个复选框的代码笔。

HTML

<html ng-app="codePen" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Multiple Checkboxes</title>
</head>
<body>
  <div ng:controller="MainCtrl">
    <label ng-repeat="tag in model.tags">
        <input type="checkbox" ng-model="tag.enabled" ng-change="onChecked()"> {{tag.name}} 
    </label>
    <p>tags: {{model.tags}}</p>
    <p> checkCount: {{counter}}  </p>
</body>
</html>

JS-

var app = angular.module('codePen', []);    
    app.controller('MainCtrl', function($scope){
        $scope.model = { id: 28329332,
        title: "checkboxes that append to a model in Angular.js",
        tags: [{
          id: 5678,
          name: "angularjs",
          enabled: false
        }, {
          id: 890,
          name: "JavaScript",
          enabled: true
        }]
        };
      $scope.counter = 0;
      $scope.onChecked = function (){
        $scope.counter++;
      };
 });

如果有人在查找这个问题,我发现了一个名为checklist模型的很棒的库,值得一提。我所要做的或多或少就是:

<div class="checkbox" ng-repeat="tag in tags">
  <label>
    <input type="checkbox" checklist-model="question.tags" checklist-value="tags"> {{ tag.name }}
  </label>
</div>

在谷歌上搜索"角度复选框指令"时发现了这一点。