0

鉴于以下 Angular 1.5 组件控制器...

'use strict'

 function MyController($http){

    //The template variable for cloning on a form
    this.myVarTemplate = {};
    //The Data I wish to send to the server
    this.myVarTemplate.data = {};
    //Other form specific / callback data
    this.myVarTemplate.meta = {};
    this.myVarArray = [];
    //A container of raw data I'm parsing for example, on whitespace bound to a text input
    this.rawInput = '';

    this.parse = function(){
        var temp = this.rawInput.split(' ');
        for( var i = 0; i < temp.length; i++){
            var container = angular.copy(this.myVarTemplate);
            container.data = temp[i];
            this.myVarArray.push(container);
        }
    }

    this.upload = function(){
        for(var i = 0; i < this.myVarArray.length; i++){
            $http({
                method: 'POST',
                url: <url here>,
                data: this.myVarArray[i]
            }).then(function(response){
                //My Success callback won't work!!!!
                //Response logs successfully, data is retrieved
                console.log(response);
                //this.myVarArray.meta is undefined??
                //console.log(this.myVarArray) is undefined
                this.myVarArray[i].meta.reply = response.data;
            }, function(message){
                //Never been an issue here
                alert('Something Bad happened? doesn't happen');
            }).finally(function(){
                //Works
                this.myVarArray[i].meta.wasSent = true;
            });
        }
    }
})

我正在尝试将一批 AJAX 查询结果返回到它们正确的相应表单对象。似乎 this.myVarArray 在 $http 服务成功回调的上下文中是未定义的。为什么是这样?这是 Angular 的怪癖还是 Javascript 本身的怪癖?我知道 $http 服务返回一个承诺,但这应该在回调的上下文中解决。为什么 myVarArray 未定义?

非常感谢您的任何见解。

编辑:修复了我的示例代码... :)

4

1 回答 1

1

this.myVarArray 是一个字符串数组,它基于从解析中的原始输入中拆分出来的内容。您正在尝试将对象属性 (.meta) 分配给字符串数组元素。您可以尝试以下方式:

this.myVarObjArray;
this.rawInput = '';

this.parse = function(){
    var temp = this.rawInput.split(' ');
    var valArray = []
    for( var i = 0; i < temp.length; i++){
        valArray.push(angular.copy(temp[i]));
        this.myVarObjArray[i] = { val: valArray};
    }

}

this.upload = function(){
    angular.forEach(this.myVarObjArray, function(obj,v){
        $http({
            method: 'POST',
            url: <url here>,
            data: obj.val
        }).then(function(response){
            //My Success callback won't work!!!!
            //Response logs successfully, data is retrieved
            console.log(response);
            //this.myVarArray.meta is undefined??
            //console.log(this.myVarArray) is undefined
            obj.meta = {reply :response.data};
....
    })

本质上是您尝试将对象属性分配给字符串数组元素。这行不通。我的语法可能不是 100%。如果你进入一个 plunker,我会为你提供一个工作示例。这应该让你走上正确的轨道。

于 2016-04-08T22:33:32.200 回答