我是新手,我使用服務從json文件中獲取數據,然後將數據返回給控制器。當我點擊按鈕時,控制器方法沒有得到執行,console.log中也沒有錯誤。我在這裏錯過了什麼?使用工廠將數據返回給控制器時出錯
我的服務代碼:
Service.js
app.factory('MovieService', function ($http) {
var url = "js/data.json";
var data;
return {
getData: function() {
return $http.get(url)
.success(function(response) {
data = response;
return data;
})
.error(function (error){
console.log("error");
})
}
};
});
Controller.js
app.controller('MainController1', ['$scope', '$log','$location','MovieService', function($scope,$log,$location,MovieService) {
console.log("click");
var getData = function() {
// This service's function returns a promise
MovieService.getData()
.then(function(data) {
// promise fulfilled
console.log("controller data");
$scope.custdata = data;
console.log($scope.custdata);
}, function(error) {
// promise rejected, could log the error with:
console.log("error");
});
};
}])
的index.html
個<div class="main" ng-controller="MainController1 as main">
<input type="button" name="getdata" value ="Get data" ng-click="main.getData()"></input>
</div>
數據
[
{
"Id": "1",
"Name": "Harry Potter"
},
{
"Id": "2",
"Name": "Jurassic Park"
}
]
控制方法應該是有界的,以'this'像'this.getData' –