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

标签 javascript angularjs yeoman

我用 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/

相关文章:

php - 在 php 代码 drupal 7 中使用 drupal_add_js

javascript - 页面重新加载后在url中添加 anchor 并在JS中显示隐藏部分

JavaScript 正则表达式 - 使用尾随零和字符串格式化十进制

javascript - AngularJS( CoffeeScript ): $interval only runs once

html - <ol> 导出数据时不符合预期

angularjs - 如何在 Angular UI Bootstrap 中查看模态是否打开

javascript - 正则表达式:如何从标签内部获取内容(使用 javascript)?

gruntjs - Grunt.Js (+ Yeoman) - 构建时复制 bower 文件

yeoman - 更新 Yeoman 生成器的首选方式是什么?

angularjs - Grunt Build 无法使用 Bower 安装的组件