2012-11-28 70 views
1

我創建了基於本教程這裏ChosenJS插件的角度指令:https://www.youtube.com/watch?v=8ozyXwLzFYsAngularJS + ChosenJS更新模型

我想要做的就是在選擇的值有模型更新。

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 
    } 
}]); 

這裏是小提琴:http://jsfiddle.net/dkrotts/MQzXq/7/。如果您選擇不同的選項,則不會更新模型值。

回答

2

如果您修改選擇綁定到legalEntity.name而不是隻是legalEntity您的小提琴的作品。

<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爲例。

2

我想添加這個作爲評論,但我缺乏聲望點。但請注意,較新版本的Chosen使用活動chosen:updated而不是liszt:updated - 感謝視頻Dustin!