//select2 documentation: http://ivaynberg.github.io/select2/index.html evoapp.directive('customCombo', function() { //http://www.befundoo.com/university/tutorials/angularjs-directives-tutorial/ //pass specified values to specified function arguments function callback(fn, args) { var fnArgs = [].concat(args); fnArgs.push.apply(fnArgs, arguments); return fn.apply(this, fnArgs); }; return { require:'ngModel', require: '^ngController', restrict: 'AE', template: '', scope: { selectedValue: '=', // =’ to accept a Object storeModel: '@', // @’ to accept a string value storeActionsGet: '@', valueField: '@', displayField: '@', addEmptyOption: '@', bindToModel: '@', itemId: '@', name: '@', //TODO: !!! optionsTemplate: '@', onChange: '&' }, controller: function($rootScope, $scope, $filter, globals, $timeout) { $scope.elem = null; //add reference to this combo, in parent controller if($scope.$parent[$scope.itemId] == undefined) { $scope.$parent[$scope.itemId] = $scope; } else { throw Error('Combo ' + $scope.itemId + ' already exists!'); } $scope.store = new globals.dataService.store({ //model: $scope.storeModel, actions: { get: $scope.storeActionsGet }, sort: $scope.displayField }); $scope.options = []; $scope.getSelected = function(record){ return record == $scope.selectedValue ? 'selected' : ''; }; $scope.$watch('selectedValue', function(newValue, oldValue){ $scope.selectedValue = newValue; }); $scope.loadStore = function(){ var callBackFn = arguments.length == 1 ? arguments[0] : null; callBackFn = angular.isFunction(callBackFn) ? callBackFn : null; $scope.store.get(function(response, status, headers, config, items){ $scope.options = $scope.store.items; if(callBackFn != null) { callback(callBackFn, [response, status, headers, config, items]); } }); }; $scope.setValue = function(newValue){ //$scope.$apply(function () { // $scope.selectedValue = newValue; //}); $scope.selectedValue = newValue; $($scope.domEl).select2('data', newValue); }; $scope.loadData = function(data){ $scope.store.items = []; $scope.options = []; $scope.store.loadData(data); $scope.options = $scope.store.items; }; }, link: function (scope, elem, attrs, controller) { scope.name = attrs.name == undefined ? scope.valueField : attrs.name; scope.elem = elem; scope.domEl = $(elem.find('select')[0]); scope.domEl.attr('name', scope.name); $(scope.domEl).select2({ allowClear: true }).on("change", function(e) { var record = angular.element($(this).find("option:selected")).scope(); if(record) { var value = $(this).find("option:selected").val(); scope.$apply(function () { if(scope.bindToModel === 'true') { scope.selectedValue = value; scope.selectedRecord = record.item; } scope.onChange({ selectedValue: value, selectedRecord: record.item }); elem.blur(); }); } }); } } });