Ошибка при использовании фильтра для значений из $http.get

Я использую фильтр для извлечения идентификатора из повторителя. Все работает, но в консоли выдает следующую ошибку:

https://docs.angularjs.org/error/$interpolate/interr?p0=%7B%7BspecsList%20%7C%20splitIds%7D%7D&p1=TypeError:%20Cannot%20read%20property%20%27map%27%20of%20undefined

Если я заменю $http.get статическими значениями для specsList, ошибки не будет. Любая идея о том, как обойти это в хорошем смысле?

JS:

app.controller('SpecsController', function ($scope, $http) {
    $scope.$on('$viewContentLoaded', function(event) {
      $http.get('getSpecs.aspx')
          .then(function(result) {
            $scope.specsList = result.data.specs;
          })
          .catch(function(err) {
            console.log(err);
          });
    });

    $scope.sortableOptions = {
        handle: "> .position",
        helper: function (e, ui) {
              var originals = ui.children();
              var clonedHelper = ui.clone();
              clonedHelper.children().each(function(index) {
                 //$(this).width($(this).width());
                 $(this).width(originals.eq(index).outerWidth());
                 $(this).addClass("dragging");
                 $(this).parent().addClass("dragging_tr");
              });
              return clonedHelper;
        },
        update: function(e, ui) {
            //console.log("update");
        },
        stop: function(e, ui) {
            //Save sortorder
        }
    };
});

app.filter('splitIds', function() {
  return function(ArrayWithIds) {
      return ArrayWithIds.map(function(item){return item.id;}).join();
  };
});

HTML:

<input type="text" value="{{specsList | splitIds}}" />

person peta    schedule 10.09.2014    source источник


Ответы (2)


Хорошо, это должно решить вашу проблему:

app.filter('splitIds', function() {
  return function(ArrayWithIds) {          
      return (angular.isUndefined(ArrayWithIds) || !angular.isArray(ArrayWithIds))?
                "":
                ArrayWithIds.map(function(item){return item.id;}).join();
  };
});

Происходит то, что первый раз, когда фильтр splitIds называется $scope.specsList, еще не существует.

person Josep    schedule 10.09.2014

Поскольку обещание возвращается, вам нужно изменить $http.get('getSpecs.aspx') на return $http.get('getSpecs.aspx')

person Pramod Karandikar    schedule 10.09.2014
comment
$http.get() вызов находится в обратном вызове события, так как же его можно вернуть? Пожалуйста, объясни. - person MiTa; 10.09.2014
comment
Я все еще получаю сообщение об ошибке с возвратом $http.get('getSpecs.aspx') - person peta; 10.09.2014