服务中的AngularJS变量未在视图中更新?

时间:2017-05-28 19:26:07

标签: angularjs service

我花了几天的时间敲打桌子,阅读博客文章,并围绕我的问题提出问题。我尝试了下面的代码的几种变体,到目前为止还没有。我将不胜感激任何帮助。

服务中的taskList变量确实更新,但控制器中的那个变量没有更新。

控制器

angular.module("TaskManager").controller("mainController", function ($scope, API) {

    $scope.init = function () {
        console.log("Initializing app");
        API.getTasks();

    }


    $scope.tasks = API.taskList;

    $scope.$watch(function(){return API.taskList}, function(newVal, oldVal){

        alert("This is tasklist in controller" + newVal);
    }, true)


});

服务

angular.module("TaskManager").service("API", function ($http, $rootScope) {

    const apiKey = "PUH";
    var taskList = [1,2,3,4];
    const getTasks = function () {
        $http.get("https://api.mlab.com/api/1/databases/jquerytaskmanager/collections/tasks?apiKey=" + apiKey).then(function (data) {
           taskList = data; 
           console.log(taskList);
        });
    };

    $rootScope.$watch(function(){return taskList}, function(newVal, oldVal){

        alert(taskList);
        taskList = newVal;


        console.log(taskList);

    }, true)

    return {
        getTasks,
        taskList

    }
});

查看

<div class="row">
    <div class="col s12">

        <ul id="mainMenu" class="right hide-on-med-and-down">
            <li><a class="waves-effect waves-light btn blue darken-4"><i class="fa fa-bars" aria-hidden="true"></i> Menu</a></li>
            <li><a class="waves-effect waves-light btn blue darken-4"><i class="fa fa-plus" aria-hidden="true"></i> Add Task</a></li>
            <li><a class="waves-effect waves-light btn blue darken-4"><i class="fa fa-pencil" aria-hidden="true"></i> Manage Categories</a></li>
        </ul>

    </div>

</div>

<div class="mainContainer container">
    <div class="row">
        <div class="col 6">
            <h2>Tasks</h2>



        </div>

    </div>



            <ul>
                <li class="taskContainer" ng-repeat="task in tasks" >

                    <div class="row">
                        <div class="col s6">
                             <span class="taskName"> {{task.task_name}}</span> 
                        </div>

                        <div class="col s6">
                            <button class="btn blue darken-4 waves-effect waves-light  ">Edit</button> <button class="btn red darken-4 waves-effect waves-light ">Delete</button>
                        </div>

                    </div>


                </li>

            </ul>








</div>

1 个答案:

答案 0 :(得分:1)

从服务中返回$ http承诺:

app.service("API", function($http) {
    this.getTasks = function() {
        return $http.get(url);
    };
});

然后在控制器中,从promise中提取数据:

app.controller("mainController", function($scope, API) {
    this.$onInit = function () {
        console.log("Initializing app");
        API.getTasks().then(function(response) {
            $scope.tasks = response.data;
        });    
    };
});

有关详细信息,请参阅AngularJS $http Service API Reference