2014-03-07 65 views
0

嗨我有以下問題,在此先感謝您的幫助。

假設我有我的服務器上的文件data.json:

{"name": "World"} 

假設我有以下main.html中

<!doctype html> 
<html> 
    <head></head> 
    <body ng-controller="mainController"> 
     Hello {{name}}! 

     <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script> 
     <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular-route.min.js"></script> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
     <script> 

      angular.module('controller.main', [], function(){ 
      }).controller('mainController', ['$scope', '$http', function($scope, $http){ 

       $scope.name = 'No Name Yet'; 

       var _this = this; 

       $http({ 
        method: 'GET', 
        url: 'data.json' 
       }).success(function(data, status, headers, config) { 
        $scope.name = data.name; 
       }). 
       error(function(data, status, headers, config) { 
        $scope.name = 'error or whatever'; 
       }); 


      }]); 

      angular.element(document).ready(function() { 
       var myApp = angular.module('myApp', ['controller.main']); 
       angular.bootstrap(document, ['myApp']); 
      }); 
     </script> 
    </body> 
</html> 

如何設置$ scope.name?

非常感謝。

回答

0

我找到了答案。

var responsePromise = $http({ 
       method: 'GET', 
       url: 'data.json' 
      }).success(function(data, status, headers, config) { 
       $scope.name = data.name; 
      }). 
      error(function(data, status, headers, config) { 
       $scope.name = 'error or whatever'; 
      });