javascript - 取消设置对象属性

标签 javascript oop object angularjs

我有一个提供商:

AdviceList.provider('$adviceList',function(){
    this.$get = function ($rootScope,$document,$compile,$http,$purr){

        function AdviceList(){

          $http.post('../sys/core/fetchTreatments.php').success(function(data,status){
                this.treatments = data;
                console.log(this.treatments); // the correct object
            });

            this.adviceCategories = [
                // available in the controller
            ];

        }
        return{

            AdviceList: function(){
                return new AdviceList();
            }
        }
    }
});

此外,我有这个 Controller :

AdviceList.controller('AdviceListCtrl',function($scope,$adviceList){
    var adv = $adviceList.AdviceList();
    $scope.treatments = adv.treatments; // undefined
});

为什么 Controller 的 $scope.treatments 保持未定义状态,而提供程序内部的 this.treatments 却被正确填充?此外,adviceCategories 在我的 Controller 中可用。

最佳答案

您收到的调用本质上是异步的,因此当您尝试分配结果时,结果可能尚未填充。

所以这里

var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments;  //The treatments would only get filled after the server call is over.

您需要重写代码,以便在成功回调时将其分配给范围属性。

关于javascript - 取消设置对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17699595/

相关文章:

javascript - 如何在发生溢出时自动向上滚动文本?

javascript - 给定相同键/值的关联数组中的连接值

php - 在继承树中获取 PHP 对象的祖先

JavaScript 更新变量

javascript - 如何使用 jquery 中的 name 属性突出显示所选表格行的颜色

perl - Perl 运行时是否有实际的派生类?

Java:静态类?

java - 使用通用网络摄像头进行对象检测

c++ - 具有多个窗口的应用程序作为类的实例,C++

java - 正则表达式括号或数字行首