Angularjs选择字段不显示选定的

时间:2015-08-23 08:03:13

标签: javascript angularjs

我有一个像这样的角度指令:

'use strict';

angular.module('countrySelect', [])
  .directive('countrySelect', ['$parse', function($parse) {
    var countries = [
      { code: "af", name: "Afghanistan" },
      { code: "ax", name: "Åland Islands" },
      { code: "al", name: "Albania" },
      { code: "dz", name: "Algeria" },
    ];

    return {
      template: '<select ng-options="c.code as c.name for c in countries">',
      replace: true,
      link: function(scope, elem, attrs) {
        scope.countries = countries;

        if (!!attrs.ngModel) {
          var assignCountry = $parse(attrs.ngModel);

          elem.bind('change', function(e) {
            assignCountry(elem.val());
          });

          scope.$watch(attrs.ngModel, function(country) {
            elem.val(country);
          });
        }
      }
    }
  }]);

模板中的选择字段如下:

<div country-select ng-model="citizenship"></div>

我可以选择一个选项,模型会根据需要使用国家/地区代码进行更新,但国家/地区名称不会出现在选择字段中,除非我再次选择它。

换句话说,过程就是

  1. 点击
  2. 选择国家/地区
  3. 模型使用国家/地区代码进行更新,但名称未显示在选择字段
  4. 点击并再次选择
  5. 名称出现在选择字段
  6. 如何在选择时让选择字段显示国家/地区名称?

2 个答案:

答案 0 :(得分:2)

由于您使用的是replace: true原始ng-model="citizenship",最终会以select元素结束,因此您无需处理选择更改事件以更新ngModel,它是已绑定选择框。所以你的指令看起来应该是这样的:

angular.module('countrySelect', [])
.directive('countrySelect', [function() {
    var countries = [
        { code: "af", name: "Afghanistan" },
        { code: "ax", name: "Åland Islands" },
        { code: "al", name: "Albania" },
        { code: "dz", name: "Algeria" },
    ];

    return {
        template: '<select ng-options="c.code as c.name for c in countries"></select>',
        replace: true,
        link: function(scope, elem, attrs) {
            scope.countries = countries;
        }
    }
}]);

演示: http://plnkr.co/edit/9aBhrlIqPIGkGTNTwIb6?p=preview

答案 1 :(得分:0)

您可能希望使用GET / POST来强制更新&#34;风景。 http://jimhoskins.com/2012/12/17/angularjs-and-apply.html