AngularJS,我的第一个html组件"widget"

AngularJS, my first html component "widget"

本文关键字:quot widget 组件 html 我的 第一个 AngularJS      更新时间:2023-09-26

我用yeoman生成了我的第一个AngularJS应用https://github.com/yeoman/generator-angular

我创建了我的第一条路由,目前正在努力在指令上写什么,在控制器上写什么,如何在我从POST或PUT接收的APIService中指定JSON消息(我有一个后端准备好了).

我创建了一个新的服务,并试图扩展一个代码,但我得到的错误:无法读取属性'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;
});

这是控制器中的代码:

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,

这可能会帮助您查看

我已经添加了一些示例代码,但如果你需要一些虚拟数据从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;
});