我正在根据此处的教程为 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/