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

Sha*_*han 7 angularjs jquery-select2 ng-options

我在创建新帖子时使用select2创建一个带有功能标签的div.

Stack是Angular 1.6.x.

当我在创建新帖子时,它很有效.但是当我在编辑所述帖子时添加预先选择的值时,预选值永远不会从默认值更改.

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

见下文:

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>
Run Code Online (Sandbox Code Playgroud)

注意:它看起来很乱,但是我得到这个来显示我的原始标签

控制器片段:

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

$scope.updatePost = function() {
  console.log($scope.post.tags);
};
Run Code Online (Sandbox Code Playgroud)

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

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

很丢失.任何意见都将受到高度赞赏.

谢谢

编辑 - 2018年4月28日:

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

[
  {tag: "tag1", _id: "5ae410756b7a61080cd17c81"},
  {tag: "tag2", _id: "5ae410756b7a61080cd17c80"},
  {tag: "tag3", _id: "5ae410756b7a61080cd17c7f"}
]
Run Code Online (Sandbox Code Playgroud)

当我这样做时它仍然不起作用:

<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>
Run Code Online (Sandbox Code Playgroud)

console.log仍然只捕获预先存在的标记.新的被忽略了.

Abh*_*ngh 4

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

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>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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