【问题标题】:AngularJS ng-init does not workAngularJS ng-init 不起作用
【发布时间】:2016-09-09 17:46:36
【问题描述】:

当我在加载页面后立即转到 list.html 时,它不会向我显示列表。我需要先访问 form.html,然后再返回 list.html,然后它会为我提供列表。当我在控制器中有 $http 函数时,它可以按我的意愿工作,但现在它们正在服务中,它们不像以前那样工作了。

app.js

app.service("dataservice", function($http){

    var list = [{}];

    this.get = function(){
        $http.get("harjoitus22/backend.php").success(function(response){
            list = response;
        });
    };

    this.save = function(newcontact){

        $http({
            method: 'post',
            url: 'harjoitus22/backend.php',
            data: newcontact,
            header: 'Access-Control-Allow-Origin: *'
        }).success(function(response){
            list = response;            
        });         
    }; 

    this.give = function(){
        return list;
    };
});

app.controller("mainController", function($scope, $location, dataservice){

    $scope.save = function(){    
        dataservice.save($scope.newcontact);
        $scope.newcontact = {};
        $location.path("/list");
        $scope.list = dataservice.give();
    };

    $scope.get = function(){
        dataservice.get();
        $scope.list = dataservice.give();
    };
});

list.html

    <tbody ng-init="get()">
        <tr ng-repeat="object in list">
            <td>{{object.nimi}}</td>
            <td>{{object.email}}</td>
            <td>{{object.ruoka}}</td>
            <td>{{object.sauna}}</td>
        </tr>
    </tbody>

【问题讨论】:

    标签: javascript angularjs angular-promise angularjs-http ng-init


    【解决方案1】:

    $http 调用异步工作,当你调用它时,它不会在下一行执行时给你响应。要密切关注该 ajax,您应该使用 promise return by $http 方法。

    为了达到同样的效果,您需要从服务get 方法返回promise 对象($http 方法确实返回了promise 对象,它可以帮助您通过放入它的.then 函数来执行您的代码)。

    服务

    this.get = function(){
        return $http.get("harjoitus22/backend.php").then(function(res){
            list = res.data;
        });
    };
    

    控制器

    dataservice.get().then(function(){
       $scope.list = dataservice.give();
    });
    

    【讨论】:

    • 不是“可以”,而是“应该”呵呵
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多