angularjs ng-options with custom filter not working

ε祈祈猫儿з 提交于 2019-12-11 05:17:02

问题


Sorry to ask this question again but no answer or workaround has been identified.

This is a follow-up of this question : Stackoverflow

I have a plunker which describes the issue (basically putting a tree structure in a dropdown list) :

Plunker example

As illustrated the first select does not select the value and gets back to an empty line - which is also a mystery.

I have not been able to find any similar cases and I am close to giving up so this is the last chance.

Key code areas are the filter and the initTreeSelect function :

$scope.initTreeSelect = function(tree){
   $scope.filteredFields = $filter('flattenTree')(tree);
   return $scope.filteredFields[0];

};


angular.module('myApp.filters', []).filter('flattenTree', function (OrgSvc) {
return function (array) {
  var arrayToReturn = [];        
    arrayToReturn = OrgSvc.flattenTree(array);
    return arrayToReturn;

};})

Your help would be very much appreciated! Thanks


回答1:


What Dayan Moreno Leon wrote in his answer is actually correct. And the problem really is that angular keeps losing track of the model data (because by default objects/arrays are identified by reference).

This is thwarted, because your flattenTree keeps returning newly created objects:

flatTree.push({id:tree[i].id, display:tree[i].display, parentId:tree[i].parentId});

For your concrete problem though, I think using track by will help, e.g.:

<select
  class='form-control' 

  ng-model="treeValue1"
  ng-init="treeValue1 = initTreeSelect(fields)"
  ng-options="element as element.display for element in fields | flattenTree track by element.id"
></select>  

demo: http://plnkr.co/edit/J8PyypC61uzx8PPNV6Zu?p=preview



来源:https://stackoverflow.com/questions/24512041/angularjs-ng-options-with-custom-filter-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!