Angular JS - 自定义过滤器 - 竞争条件错误

时间:2016-07-30 22:51:46

标签: angularjs angular-filters angular-components

嗯,我的问题很简单,是一个竞争条件错误,我的数组不是在过滤器尝试使用它时创建的,但是当页面完成加载一切它工作正常时,我在控制台中有几个错误在页面完全像这样加载:

TypeError: Cannot read property 'forEach' of undefined
at eval (eval at <anonymous> (index.js:60), <anonymous>:25:10)
at fn (eval at compile (eval at <anonymous> (index.js:142)), <anonymous>:4:565)
at regularInterceptedExpression (eval at <anonymous> (index.js:142), <anonymous>:15831:55)
at Scope.$digest (eval at <anonymous> (index.js:142), <anonymous>:17277:34)
at Scope.$apply (eval at <anonymous> (index.js:142), <anonymous>:17552:24)
at done (eval at <anonymous> (index.js:142), <anonymous>:11697:47)
at completeRequest (eval at <anonymous> (index.js:142), <anonymous>:11903:7)
at XMLHttpRequest.requestLoaded (eval at <anonymous> (index.js:142), <anonymous>:11836:9)

和其他人问我有,为什么这个错误会出现13次?我不能自己回复。

这是我的代码:

模板HTML

<ul style="list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;">
<li style="float: left;"><button ng-click="$ctrl.setFilterContacts('')">Todos</button></li>
<li style="float: left;"><button ng-click="$ctrl.setFilterContacts('j')">a</button></li>
<li style="float: left;"><button ng-click="$ctrl.setFilterContacts('m')">b</button></li>
</ul>
<intelico-contact ng-repeat="contact in ($ctrl.contacts | orderBy: 'name' | startsWithLetter: $ctrl.getFilterContacts())" contact="contact">
 </intelico-contact>

模块创建:

import angular from 'angular';

import {contact} from './contact';
import {contacts} from './contacts';
import {contactDetail} from './contact-detail';

export const contactsModule = 'contacts';

angular
  .module(contactsModule, [])
  .component('intelicoContact', contact)
  .component('intelicoContacts', contacts)
  .component('intelicoContactDetail', contactDetail)
  .filter('startsWithLetter', function(){
    return function(items, letter){
      var contactsFiltered = [];
      items.forEach(function (item) {
        var name = item.name.toLowerCase();
        if (name.startsWith(letter)){
          contactsFiltered.push(item);
        }
      })
      return contactsFiltered;
    };
  });

控制器(组件定义)

class ContactsController{
  /** @ngInject */
  constructor($http) {
    this.filterSelected = '';
    $http
      .get('app/contacts/contacts.json')
      .then(response => {
        this.contacts = response.data;
      });

  }

  getContacts(){
    return this.contacts;
  }

  setFilterContacts(filter){
    this.filterSelected = filter;
  }

  getFilterContacts(){
    return this.filterSelected;
  }
}

export const contacts = {
  templateUrl: 'app/contacts/contacts.html',
  controller: ContactsController
};

0 个答案:

没有答案