ng-options 在具有预选值时不绑定

ng-options not binding when it has preselected values

我正在使用 select2 创建一个 div,在创建一个新的 post 时带有类似功能的标签。

堆栈是 Angular 1.6.x

当我创建新的 post BUT 时效果很好,当我在编辑上述 post 时添加预选值时,预选值从不更改默认值。

简而言之,这些值没有约束力。

见下文:

HTML 片段:

<div class="form-group">
  <label for="tags" class="control-label">Tags</label>
    <select name="tags" class="tagsSearch" class="form-control" id="tags"
            ng-options="tag as tag for tag in post.tags track by tag"
            ng-model="post.tags" style="width: 100%" multiple>
    </select>
</div>

注意:它看起来很乱,但我用它来显示我的原始标签

控制器片段:

$http.get('/api/post', {params: { title: $scope.title }})
.then(function(res){
   $scope.post = res.data.post;
});

$scope.updatePost = function() {
  console.log($scope.post.tags);
};

问题是标签没有绑定,所以如果值是:tag1、tag2、tag3 在渲染时我添加:tag4 - updatePost 控制台 tag1、tag2 和 tag3

PS:我的标签是一个字符串数组,没有像 ID 那样的键(看到其他一些 post 引用了它们)。

很失落。任何输入将不胜感激。

谢谢

编辑 - 2018 年 4 月 28 日:

我已将我的标签更新为如下数组的对象:

[
  {tag: "tag1", _id: "5ae410756b7a61080cd17c81"},
  {tag: "tag2", _id: "5ae410756b7a61080cd17c80"},
  {tag: "tag3", _id: "5ae410756b7a61080cd17c7f"}
]

我这样做还是不行:

<select name="tags" class="tagsSearch" class="form-control" id="tags"
        ng-options="tag as tag.tag for tag in post.tags track by tag._id" 
        ng-model="post.tags" style="width: 100%" multiple>
</select>

console.log 仍然只捕获预先存在的标签。忽略新的。

试试看是否可行:

ng-options="tag as tag for tag in post.tags track by tag.id"

仅更改为 tag.id 跟踪。如果标签对象中有不同的键,也可以使用它来代替 id。

具有该更改的 HTML 片段:

<div class="form-group">
  <label for="tags" class="control-label">Tags</label>
  <select name="tags" class="tagsSearch" class="form-control" id="tags"
          ng-options="tag as tag for tag in post.tags track by tag.id"
          ng-model="post.tags" style="width: 100%" multiple>
  </select>
</div>

ng-model 持有相同的数组 post.tags。请使用不同的 ng-model 来保存所选标签。

HTML:

<div ng-controller="MyCtrl">
    <!-- this list is for assure, that two way binding works -->
    List of Tags:
  <ul>
        <li data-ng-repeat="tag in post.tags">{{tag.tag}}</li>
    </ul>
  <br>
  Select Tags: <!-- selected items are not binded to the model -->
    <select multiple ui-select2 class="form-control" data-ng-model="selectedTags" >
        <option data-ng-repeat="tag in post.tags" value="{{tag._id}}" text="">{{tag.tag}}</option>
    </select>
</div>

控制器:

var myApp = angular.module('myApp', ['ui.select2']);

function MyCtrl($scope) {
    $scope.selectedTags = [4]; // Averell is preselected (id:4)
    $scope.post = {
       tags: [
    {tag: "Angular JS", _id: "5ae410756b7a61080cd17c81"},
    {tag: "Java", _id: "5ae410756b7a61080cd17c80"},
    {tag: "JQuery", _id: "5ae410756b7a61080cd17c7f"}
  ]};
};

请检查此 DEMO 并检查您是否找到了所需的内容。

我使用 angular select 文档作为参考,并根据他们的示例创建了一个 plunker here

我用这个blob来模拟你的数据集。

这就是我的 select 指令的样子。我建议您不要用 selected 项目的绑定覆盖数组的绑定,这就是导致您出现问题的原因。

(function(angular) {
  'use strict';
angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope','$http', function($scope,$http) {
    var url = "https://jsonblob.com/api/jsonBlob/aa6b4eb4-5284-11e8-a5ee-fd00735e3b38";
    $http
        .get(url)
        .then(function(response){
            $scope.post = {
                tag: response.data,
                selected: response.data[0]
            };
        })
 }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="mySelect">Make a choice:</label>
    <select name="mySelect" id="mySelect"
      ng-options="option.tag for option in post.tag track by option._id"
      ng-model="post.selected" multiple></select>
  </form>
  <hr>
  <tt>option = {{post.selected}}</tt><br/>
</div>
</body>

快乐编码

我认为您可以尝试从 DOM 中删除该元素,然后使用新值再次添加它。您可以将 ng-if 与标志一起使用..

<div class="form-group" ng-if="someflag">
  <label for="tags" class="control-label">Tags</label>
    <select name="tags" class="tagsSearch" class="form-control" id="tags"
            ng-options="tag as tag for tag in post.tags track by tag"
            ng-model="post.tags" style="width: 100%" multiple>
    </select>
</div>

现在要更新数据的地方,放下面代码: (注意:需要在controller中注入$timeout)

//Default Value
$scope.someflag = true;

//Update Data
$scope.myNewData = function(){
  //Remove from DOM
  $scope.someflag = false;

  //Add to the DOM with some delay
  $timeout(function(){
    $scope.someflag = true;
  })
}

下面的实现可能是您所要求的:

HTML:

 <form name="myForm">
    <label for="mySelect">Make a choice:</label>
    <select name="mySelect" id="mySelect"
      ng-options="option.tag for option in post.tag track by option._id"
      ng-model="post.selected" multiple></select>
      <br>
      <button ng-click="updatePost()"> Add Tag</button>
 </form>

JS:

(function(angular) {
  'use strict';
  angular.module('defaultValueSelect', [])
    .controller('ExampleController', ['$scope', '$http', function($scope, $http) {
      var url = "https://jsonblob.com/api/jsonBlob/aa6b4eb4-5284-11e8-a5ee-fd00735e3b38";
      var index = 4;
      var extraObj = {
        tag: "tag",
        _id: "5ae410756b7a61080cd17c7"
      };
      $http
        .get(url)
        .then(function(response) {
          $scope.post = {
            tag: response.data,
            selected: response.data[0]
          };
        });
      $scope.updatePost = function() {
        var tmp = {};
        tmp = angular.copy(extraObj);
        console.log(angular.copy($scope.post));
        tmp.tag += index;
        tmp._id += index;
        $scope.post.tag.push(tmp);
        console.log($scope.post);
        index++;
      }
    }]);
})(window.angular);

有关工作代码,请参阅此 plunkr:plnkr。co/edit/cwDRa2Qjg2IlUi5JOAPj