将数据从数据库获取到角度js

时间:2014-06-20 03:47:39

标签: javascript php json angularjs http

我是Angular 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 ,您应该看到此输出“您已连接到我的php文件”,但正如我之前所说,数据似乎永远不会更新到变量:

this.content

非常感谢你的帮助

Juan Camilo Guarin P

2 个答案:

答案 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
    });

}]);

答案 1 :(得分:1)

这里没有加载数据,因为最初&#34;内容&#34;是原始的。 你有两种方式:init&#34; content&#34;作为对象或像这样写作:

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

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