javascript - AngularJS + ChosenJS 更新模型

标签 javascript angularjs

我正在根据此处的教程为 ChosenJS 插件创建一个 Angular Directive(指令):https://www.youtube.com/watch?v=8ozyXwLzFYs

我想做的是在选择一个值时更新模型。

function Foo($scope) {
  $scope.legalEntitiesList = [
      { name: 'Foo' },
      { name: 'Bar' }      
  ];

  $scope.legalEntity = { name: 'Foo' };
}

myApp.directive('chosen', ['$timeout', function($timeout) {
  var linker = function(scope, element, attrs, ngModel) {
    if (!ngModel) return;

    element.addClass('chzn-select');

    $(element).chosen()
            .change(function(e) {
                console.log(ngModel.$viewValue);
            });

    scope.$watch(attrs.chosen, function() {
        $(element).trigger('liszt:updated');
    });
  }

  return {
    restrict: 'A',
    scope: true,
    require: '?ngModel',
    link: linker
  }
}]);

这是一个 fiddle :http://jsfiddle.net/dkrotts/MQzXq/7/ .如果您选择不同的选项,则不会更新模型值。

最佳答案

如果您修改选择以绑定(bind)到 legalEntity.name 而不仅仅是 legalEntity 您的 fiddle 会起作用。

<select id="legalEntityInput" chosen="legalEntitiesList" ng-model="legalEntity.name" ng-options="legalEntity.name for legalEntity in legalEntitiesList" data-placeholder="Select..."><option></option></select>

查看此 updated fiddle举个例子。

关于javascript - AngularJS + ChosenJS 更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13612753/

相关文章:

javascript - 使用 Apache 作为后端 JavaScript (Strapi) 服务器的代理

javascript - jQuery - 如何替换部分页面?

javascript - Angular 和 JSON 交互?

javascript - Ionic Angular/为什么在 Controller 功能结束之前不调用服务

javascript - ng-disabled 无法正常工作 5

javascript - 如何根据所选复选框的选择启用/禁用输入文本

javascript - 通过javascript/html访问twitter share iframe

javascript - 限制跨域 Ajax 请求

javascript - Firefox sdk - 内容脚本无法访问 self.port

javascript - mongodb stitch 返回所有字段