如何从stateProvider中删除状态

时间:2015-03-03 07:47:10

标签: angularjs angular-ui-router

从cacheTemplate中移除$ stateProvider及其缓存中的状态后,在尝试添加相同的州名时,它会给出“已定义”错误。

 clearStates: function () {
        var states = this.$state.get();
        for (var i = 0; i < states.length; i++) {
            if (states[i].name != 'shell.error404' &&
                states[i].name != 'shell.error500' &&
                states[i].name != 'shell' &&
                states[i].name != '') {
                var tmplUrl = states[i].templateUrl;
                if (tmplUrl) {
                    this.templateCache.remove(tmplUrl);
                }
                delete states[i];
            }
        }
    }

任何方式这样做?

1 个答案:

答案 0 :(得分:0)

尝试

 clearStates: function () {
            var states = this.$state.get();
            var itemsToBeRemoved = [];
            var removalIndex = 0;
            for (var i = 0; i < states.length; i++) {
                if (states[i].name != 'shell.error404' &&
                    states[i].name != 'shell.error500' &&
                    states[i].name != 'shell' &&
                    states[i].name != '') {
                    var tmplUrl = states[i].templateUrl;
                    if (tmplUrl) {
                        this.templateCache.remove(tmplUrl);
                    }
                    //delete states[i];
                    itemsToBeRemoved[removalIndex++] = i;
                }
            }
            for(var j=0;j<itemsToBeRemoved.length;j++){
               states.splice(itemsToBeRemoved[j],1);
             }
        }

存储要删除的索引并使用states.splice(&gt; index&lt;,1)而不是删除状态[i]

delete在给定索引处的数组中留下一个空元素,这可能是导致问题的原因。