将JSON文件导入到Grunt服务器上运行的Angular应用程序中
Importing JSON file into Angular application running on Grunt server
我正在遵循基本的Angular教程,需要在其中包含一个JSON文件。我用Yeoman启动了我的应用程序,它正在咕噜咕噜地运行。
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function PhoneListCtrl($scope) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
});
但是,当我转到localhost:9000时,我收到一堆控制台错误:
ReferenceError: $http is not defined
at new PhoneListCtrl (http://localhost:9000/scripts/controllers/main.js:17:3)
at invoke (http://localhost:9000/bower_components/angular/angular.js:3000:28)
at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:3012:23)
at http://localhost:9000/bower_components/angular/angular.js:4981:24
at http://localhost:9000/bower_components/angular/angular.js:4560:17
at forEach (http://localhost:9000/bower_components/angular/angular.js:137:20)
at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:4545:11)
at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:4191:15)
at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:4194:13)
at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:4096:30)
任何帮助将不胜感激!
最好将
json 文件包含在工厂服务中。这样,您可以缓存它并继续将其与不同的控制器一起使用。
我有一个类似的问题,并像这样解决了它......
var App = angular.module('App', []);
// Setting up a service to house our json file so that it can be called by the controllers
App.factory('service', function($http) {
var promise;
var jsondata = {
get: function() {
if ( !promise ) {
var promise = $http.get('src/data_json.js').success(function(response) {
return response.data;
});
return promise;
}
}
};
return jsondata;
});
App.controller('introCtrl', function (service , $scope) {
service.get().then(function(d) {
$scope.header = d.data.PACKAGE.ITEM[0]
})
});
App.controller('secondCtrl', function (service , $scope) {
service.get().then(function(d) {
$scope.title = d.data.PACKAGE.ITEM[1]
})
});
将$http
添加为依赖项,在function PhoneListCtrl($scope, $http) {}
$scope
旁边
相关文章:
- 如何在运行时在angular 2中加载外部js脚本
- 在其他javascript框架模板中运行angular指令
- Jhon Papa Angular Style guide Factory-对象内部的函数未运行
- Angular Promise未同步运行
- 在运行时从Angular注入器检索实例
- Kendo Grid:我们可以用jsfiddle运行Angular的例子吗
- 如果范围值更新,则运行Angular指令
- 如何在windows平台上创建和运行angular 2程序
- 在第一次服务完成后运行Angular服务
- 运行angular.js作为回调(例如$.ajax)
- 避免运行Angular Controller两次/Ajax调用
- 如何在没有浏览器同步和node的情况下运行Angular 2应用
- 在整个页面加载后运行angular
- 无法从codenvy预览/运行angular.js项目
- 我可以以60fps的速度运行angular's digest loop来显示快速计时器吗?
- 如何在无头服务器上运行angular-phonecat教程测试?
- 在Protractor中,是否可以运行Angular模块函数?
- IE9抛出错误:'错误:Microsoft Internet扩展出现内部错误'运行angular应用程序
- 控制器中的文本从未记录/从未运行Angular Rails
- 在DOM完全加载后再运行Angular指令