我用 yeoman 生成了我的第一个 AngularJS 应用程序 https://github.com/yeoman/generator-angular
我创建了我的第一个路由,目前正在努力解决在指令上写什么、在 Controller 上写什么、如何在我从 POST 或 PUT 收到的 APIService 中指定 JSON 消息(我已经准备好后端)..
我与 yeoman 一起创建了一项新服务,并尝试扩展代码,但收到错误:无法读取未定义的属性“then”。服务中的代码是:
angular.module('baApp').service('myService', function ($http, $q) {
this.getTiers = function(){
$http.get('/data/tiers.json').success(function (data) {
console.log('$http tiers');
console.log(data);
});
};
this.getCapabilities = function(){
$http.get('/data/capabilities.json').success(function (data) {
console.log('$http capabilities');
console.log(data);
});
};
return this;
});
这是 Controller 中的代码:
angular.module('baApp')
.controller('MyappCtrl', function ($scope, myService) {
myService.getTiers().then(function(res){
$scope.tiers = res;
console.log('Tiers');
console.log(res);
});
myService.getCapabilities().then(function(res){
$scope.capabilities = res;
console.log('Capabilities');
console.log(capabilities);
});
});
最佳答案
@Micky,
这可能对您有帮助 jsfiddle
我添加了一些示例代码,但是如果您需要来自 api 的一些虚拟数据直到它准备好,那么您可以使用 json 来模拟 api 响应。
这是示例代码
var app = angular.module('myApp', []);
app.controller('ctrl',function($scope, myService){
myService.getData().then(function(res){
$scope.data = res;
});
});
//service here
app.service('myService', function($http, $q){
var responseJson = {'message':'welcome to angular'}
this.getData = function(){
// call api or json file
// like
//return $http.get('api url or /test.json').
// fake response here
var deferred = $q.defer();
deferred.resolve(responseJson);
return deferred.promise;
}
return this;
});
关于javascript - AngularJS,我的第一个 html 组件 "widget",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39698305/