2015-12-30 2 views
0

Я использую acute.select в моем проекте angularjs. У меня есть array:angularjs - обновить `sharp.select` список после` ac-change`

$scope.users = []; 
$scope.acuteusers =[{UserName:"john"},{UserName:"joe"},{UserName:"mary"}]; 

     $scope.stateSelected = function(state){ 
      console.log(state); 
      for (var i = 0; i < $scope.acuteusers.length; i++) { 
       if (state.UserName == $scope.acuteusers[i].UserName) { 
        $scope.acuteusers.splice(i,1); 
       }; 
      }; 
      console.log($scope.acuteusers); 
     } 

и html:

<select class="ac-select stateList" ac-model="users" ac-options="s.UserName for s in acuteusers" 
     ac-settings="{ comboMode: true, loadOnOpen: true, minWidth: '470px' }" ac-change="stateSelected(value)" > 
     </select> 

Я хочу, чтобы вынуть элемент из выпадающего списка acute.select все выбран элемент. Но как-то он останется в качестве начальных состояний (ни один элемент не удаляется), даже console.log покажет, что он уже вынут. Как я могу это разрешить?

+0

Возможно, это проблема в вашем 'ac-'. добавьте $ timeout во время сращивания, иногда требуется время для запуска '$ digest'. –

+0

Я думаю, что сплайсинг должен быть как $ scope.acuteusers.splice (i, 1); – Nir

+0

Никогда не изменяйте массив во время итерации по нему, это анти-шаблон. Если вам нужно удалить элементы из массива во время итерации по нему, сделайте это назад (запустите счетчик с помощью 'array.len' и уменьшите его). –

ответ

0

После долгих чтений об изолированных объектах для директив (link1, link2) я решил взломать директиву acute.select.js.

Сначала я добавляю в новом scope data в acute.select.js:

.directive("acSelect", function($parse, acuteSelectService) { 
    var defaultSettings = acuteSelectService.getSettings(); 
    return { 
     restrict: "EAC", 
     scope: { 
      "acSettings": "@", 
      "acOptions": "@", 
      "model": "=acModel", 
      "acChange": "&", 
      "keyField": "@acKey", 
      "acRefresh": "=",///I believe you can use this, but no documentation at all. 
      "acFocusWhen": "=", 
      "id": "@", 
      data:"=acuteOptions"///newly added by me. 
     }, 
replace: true, 
     templateUrl: defaultSettings.templatePath + "acute.select.htm", 
     link: function(scope, element, attrs) { 
      scope.initialise(); 

      ///**Then I added in $watchCollection to watch the `data` changes. 
      scope.$watchCollection('data', function(newVals, oldVals) { 
      ///**I found out scope.allItems is the array to build and display the list. 
///however it must follow {text,value,index} object format. So I reformat it that way. 
      scope.allItems = []; 
      for (var i = 0; i < newVals.length; i++) { 
      scope.allItems.push({text:newVals[i].UserName,value:newVals[i],index:i}); 
      }; 
      }, true); 
     }, 

в html, добавьте в acute-options:

<select class="ac-select stateList" ac-model="users" acute-options="acuteusers" ac-options="s.UserName for s in acuteusers" 
     ac-settings="{ comboMode: true, loadOnOpen: true, minWidth: '470px' }" ac-change="stateSelected(value)" > 
     </select> 

Теперь, когда $scope.acuteuser изменения, это изменит выпадающий список.

Я все еще верю, что acRefresh может выполнить эту работу, но я просто не могу понять, как это сделать. Будет хорошо, если кто-то может поделиться более надежным решением.

Смежные вопросы