angular 1.6.7简单选择绑定不设置选择值

时间:2017-12-19 05:57:48

标签: javascript angularjs

(function(angular) {
  'use strict';
  angular.module('myApp', [])
    .controller('Controller', [function() {
      this.model = {
        person: {
          titleId: 4
        }
      }
    }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller as nb">
    <select ng-model="nb.model.person.titleId">
          <option value="1">A</option>
          <option value="2">B</option>
          <option value="3">C</option>
          <option value="4">D</option>
      </select>
      
      <p>{{nb.model.person.titleId}}</p>
  </div>
</div>

当我选择ABCD时,模型值会按预期更新。 person的{​​{1}}值介于1和4之间。

但是在使用titleId

加载新模型时
titleId

未将选择设置为正确的值。模型绑定似乎是单向工作,而不是2路?

有一种简单的方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

您应将其设为"4"

&#13;
&#13;
(function(angular) {
  'use strict';
  angular.module('myApp', [])
    .controller('Controller', [function() {
      this.model = {
        person: {
          titleId: "4"
        }
      }
    }]);
})(window.angular);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller as nb">
    <div class="input-group">
      <select class="form-control" id="Person_TitleId" name="Person.TitleId" ng-model="nb.model.person.titleId">
          <option value="1">A</option>
          <option value="2">B</option>
          <option value="3">C</option>
          <option value="4">D</option>
      </select>
    </div>
  </div>
&#13;
&#13;
&#13;

但我建议您使用ngOptions

&#13;
&#13;
(function(angular) {
  'use strict';
  angular.module('myApp', [])
    .controller('Controller', [function() {
      this.model = {
        person: {
          titleId: 4
        }
      }
      this.options = [{
        label: 'A',
        titleId: 1
      }, {
        label: 'B',
        titleId: 2
      }, {
        label: 'C',
        titleId: 3
      }, {
        label: 'D',
        titleId: 4
      }]

    }]);
})(window.angular);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller as nb">
    <select ng-model="nb.model.person" ng-options="a.label for a in nb.options track by a.titleId ">          
      </select>
    <p>{{nb.model.person}}</p>
  </div>
&#13;
&#13;
&#13;