2014-06-20 35 views
1

我是Angular JS的新手,我一直在從學校學習。從數據庫獲取數據到尖角js

我有這個問題,我想不出如何解決:我想從我正在處理的一個PHP文件中獲取數據,但首先我想做一個簡短的例子,因爲一些東西只是沒有意義對我來說,是永遠不會檢索具有PHP文件的角度控制器的信息。

我上傳它在jsfiddle你可以看看,如果你想

這裏的HTML,這是很基本的:

<div ng-app="app"> 
    <div ng-controller="MyController as c"> 
     <h1>{{c.title}}</h1> 
     <p>Controller trial: {{c.content}}</p> 
    </div> 
</div> 

而且這裏JavaScript源:

var app = angular.module("app", []); 
app.controller("MyController", ['$http', function ($http) { 
    this.title = "My Title"; 
    var filecontent = "Data should be replaced"; 
    $http.get("http://www.otherwise-studios.com/example.php") 
     .success(function (data) { 
      filecontent = data; 
      //I don't know why data is not loaded here :S 
     }); 
    this.content = filecontent; 
}]); 

最後,這是我得到的輸出:

My Title 

Controller trial: Data should be replaced 

如果您訪問link我從中retreiving你應該可以看到這個輸出的信息:「你連接到我的PHP文件」,但正如我前面所說的,數據似乎永遠不會更新到變量:

this.content 

非常感謝你的一切幫助

胡安卡米洛Guarin P

回答

1

這裏沒有加載數據,因爲最初的「內容」是原始的。 你有兩種方法:初始化「內容」作爲對象或寫入像這樣:

var filecontent = "la la la", 
    that = this; 

$http.get("http://www.otherwise-studios.com/example.php") 
    .success(function (data) { 
     that.content = data; 
    }); 
+0

其實,我走了這一個,因爲我不想觸及範圍。也許將來我會用範圍。 –

1
app.controller("MyController", ['$http', '$scope' function ($http,$scope) { 
this.title = "My Title"; 
var filecontent = "Data should be replaced"; 
$http.get("http://www.otherwise-studios.com/example.php") 
    .success(function (data) { 
     filecontent = data; 
     $scope.content = filecontent; // must be within success function to automatically call $apply 
    }); 

}]); 
+0

你錯了。 「this.title」綁定到控制器,而不是範圍。 :) – Miraage

+0

非常感謝你,我測試了你的答案,它的工作:) –