javascript - 如何在AngularJS中将数据从模型异步返回到 Controller

标签 javascript angularjs asynchronous byref

我是 AngularJS 的新手,并尝试制作一个 MVC 应用程序,其中 Controller 可以连接到同一类型的多个模型。

所以:

我创建一个连接到测试模型的 Controller 以获取异步信息,例如:

function TestController($scope, Test)
{
    $scope.model = {};  

    $scope.load : function(id) {
         Test.get($scope, id);
    }
}

模型使用http协议(protocol)从服务器检索(json)信息。该模型如下所示:

myApp.factory('Test',function($http) {
    get : function(variable, id) {
        $http({
           url: 'api/load/'+id
        }).success(function(response) {
           variable.model = response;       
        });
     } 
});

名称“模型”被硬连接到 Controller 中。所以没有办法加载 在 Controller 中的第二个测试模型,因为现有的将被覆盖。

如果我改变线路:

    Test.get($scope, id);

    Test.get($scope.model, id);

模型为

     variable = response;

Angular stop 的魔力。 Controller 中的模型未更新。没有 byRef 在 JavaScript 中。

是否有解决方法,使模型可以在一个 Controller 中多次使用?

最佳答案

好吧,您不需要像这样调用服务。首先,$http 调用返回 promise ,可以使用“then”回调来处理它。因此您可以为类似的调用添加多个不同的回调。对于您的情况:

myApp.factory('Test',function($http) {
    get : function(id) {
        return $http({
            url: 'api/load/'+id
        });
    } 
});

在你的 Controller 中:

function TestController($scope, Test) {
    $scope.model = {};  

    $scope.load : function(id) {
        Test.get(id).then(function(result) {
             $scope.var1 = result;
        });

        Test.get(id).then(function(result) {
             $scope.var2 = result;
        });
    }
}

另一种方法是这样做:

myApp.factory('Test',function($http) {
    get : function(context, variable, id) {
        return $http({
            url: 'api/load/'+id
        }).success(function(result) {
            context[variable] = result;
        });
    } 
});

在你的 Controller 中:

function TestController($scope, Test) {
    $scope.model = {};  

    $scope.load : function(id) {
        Test.get($scope, 'var1', id);
        Test.get($scope, 'var2', id);
    }
}

关于javascript - 如何在AngularJS中将数据从模型异步返回到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735570/

相关文章:

Javascript 不想在循环中更改对象值

javascript - Jade 中 Angular.JS 中 $scope 的问题

javascript - 执行函数作为异步 Node.js 脚本的最后一件事

javascript - 是否有一种纯粹的基于 Promise 的映射/连接集合的方法?

c# - 无法从 Task.FromAsync 方法中的组中选择方法

javascript - 用 Javascript 找出最大的质因数

javascript - 帮助将图像动态加载到 Galleria

javascript - 为什么我的 javascript 图片库没有加载?

javascript - 为 FileDrop 动态添加放置区

angularjs - 如何在 dist 目录而不是 app 目录中运行 grunt 服务器?