javascript - 使用 Restangular 创建面向对象的 AngularJS 模型

标签 javascript angularjs restangular code-cleanup

我是 Angular 新手,正在尝试弄清楚如何创建模型来清理我的 Controller 。我正在使用 Restangular 并创建了一个返回模型对象的工厂。

我以为我可以做这样的事情......

型号

Testimonials.factory('Testimonial', ['Restangular', function(Restangular) {

    /**
     * Constructor
     */
    function Testimonial() {
        // public properties, assigned to the instance ('this')
    }

    Testimonial.prototype.all = function() {
        return Restangular.all('testimonials').getList();
    }

    /**
     * Return the constructor function
     */
    return Testimonial;
}]);

Controller

Testimonials.controller('TestimonialsController', ['$scope', 'Testimonial', function($scope, Testimonial) {

    Testimonial.all.then(function (testimonials) {
        $scope.testimonials = testimonials;
    });
}]);

我在 chome 开发工具中收到错误,TypeError:无法读取未定义的属性“then”

我怎样才能做到这一点?这是实现模型的好方法吗?

最佳答案

在您的 Controller 中,您的 all 方法中缺少括号:

更改:

 Testimonial.all.then(function (testimonials) {
        $scope.testimonials = testimonials;
 });

至:

 Testimonial.all().then(function (testimonials) {
        $scope.testimonials = testimonials;
 });

并且您还需要在工厂中返回 Testimonial 的新实例:

更改:

return Testimonial;

至:

return new Testimonial();

关于javascript - 使用 Restangular 创建面向对象的 AngularJS 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24440162/

相关文章:

AngularJS,Restangular - 在运行时设置 Restangular.baseUrl

javascript - AngularJS 和 Restangular : TypeError: Cannot read property 'then' of undefined

javascript - 如何在 ionic 中检查和请求存储权限?

javascript - 将 JSON 项插入现有数组 angularjs

如果周期性 $rootScope.$digest 生效,AngularJS $http.post 响应激活得更快

angularjs - 如何交换标签和单选按钮位置 Material AngularJS

javascript - 如何通过 Google Chart API 使用 csv 文件?

javascript - 在 Next.js 中为导航链接添加事件类

javascript - Angularjs 将表行推送到另一个表

javascript - 如何在 restangular 中使用 PUT 方法