无法在Chrome应用中使用AngularJS显示数据

时间:2014-12-18 14:31:09

标签: angularjs google-chrome-app

您好我正在构建一个Chrome应用程序,用于保存和检索服务器中的数据。将数据保存到DB时没有任何问题。但是当我试图检索时,console.log显示未定义。 Web应用程序没有此问题。

HTML

<div ng-controller="FrmController">
    <h4>Total Tasks: {{tasks.length}}</h4>
    <br/>
    <li ng-repeat="todo in tasks">
        <!--<input type="checkbox" id="myCheck" ng-click="goCats = !goCats" ng-model="todo.done" value="{{todo.task_name}}">-->
        <input type="checkbox" id="myCheck" ng-model="todo.done" value="{{todo.task_name}}">
        <span class="done-{{todo.done}}"> {{todo.task_name}}</span> 
        <span class="test">
        <a id="done-modal-button-{{todo.done}}" ng-click='onCompleteTask(todo)' ng-model="todo.done" class="btn btn-xs btn-success" ng-show="todo.done">Done</a> 
        <!--<a ng-click='editTask(todo)' editable-text="{{todo.task_name}}" class="btn btn-xs btn-warning">Edit</a>-->
        <a id="delete-modal-button" ng-click='taskDelete(todo)' class="btn btn-xs btn-danger" ng-show="todo.done">Delete</a>
        </span>
    </li>
</ul>

JS

function FrmController($scope, $http) { 
 var page = "http://localhost:8080/fetch_task.php";
$http.get(page).success(function(response) {$scope.tasks = response;});
console.log($scope.tasks);
}

Console.log显示未定义。我很困惑。

1 个答案:

答案 0 :(得分:1)

此函数调用是异步的。这意味着:

function FrmController($scope, $http) { 
  var page = "http://localhost:8080/fetch_task.php"; // 1st to be executed
  $http.get(page).success( // 2nd to be executed, but it only initiates the request
    function(response) { // will be executed later, only when the response is ready
      $scope.tasks = response;
    }
  );
  console.log($scope.tasks); // 3rd to be executed - not assigned yet
}

This article使用promise机制很好地概述了它的工作原理。一个人执行一个稍后会产生结果的函数,并指出如何处理结果 - 但不会立即完成。

例如,如果你写了

function FrmController($scope, $http) { 
  var page = "http://localhost:8080/fetch_task.php";
  $http.get(page).success(
    function(response) {
      $scope.tasks = response;
      console.log($scope.tasks);
    }
  );
}

它会起作用。