使用带有原型的角度控制器

时间:2015-08-11 01:58:21

标签: javascript angularjs

我的问题很简单。

可以使用带有原型的角度控制器吗?

'use strict';
var EventController = function(scope, EventModel) {
    this.scope      = scope;
    this.EventModel = EventModel;
};

EventController.prototype = {
    create: function() {
        this.scope.create = function() {
            this.EventModel.Model.insert()
                .then(function(result) {

                });
        };
    },

    retrieve: function() {
        var that = this;

        this.EventModel.Model.find()
            .then(function(result) {
                that.scope.events = result;

            });
    },

    retrieveOne: function(id) {
        this.EventModel.Model.findOne(id)
            .then(function(result) {
                console.log(result);

            });
    },

    update: function() {
        this.EventModel.Model.update()
            .then(function(result) {

            });
    },

    delete: function() {
        this.EventModel.Model.remove()
            .then(function(result) {

            });
    }
};

module.exports = function(adminApp) {
    adminApp
        .controller('EventController', ['$scope', 'EventModel', function(scope, EventModel) {
            return new EventController(scope, EventModel);

        }]);
};

我正在使用Browserify,这就是为什么我在决赛中有这个模块.exports。

我希望以这种方式使用控制器,并将方法视为原型中对象的名称。

我有什么方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

你绝对可以。这是我用你的类似代码制作的演示。

这就是“Controller as”语法,它是在Angular 1.2.0中引入的。

演示中有三个按钮。一个人按照你的要求使用控制器本身的原型方法,另外两个说明你可以继续使用你可能习惯的控制器,通过在标记中完全使用范围,并提供范围方法在控制器中。

https://jsfiddle.net/scarl3tt/3copx1rk/1/

的Javascript

'use strict';
var TestController = function(scope) {
    this.scope      = scope;
};

TestController.prototype = {
    doAThing: function() {
        alert('This is a thing');
    }
};

angular.module('testApp', [])
    .controller('TestController', ['$scope', function(scope) {
        if(typeof(scope.extension) === 'undefined')
            scope.extension = function() {
                scope.j *= 2;
            };
        return new TestController(scope);
    }]);

标记

<div ng-app="testApp" ng-controller="TestController as ctrl" ng-init="i = 0; j = 1;">
    <h1>Controller as:</h1>
    <button ng-click="ctrl.doAThing()">Do a thing!</button>
    <h1>Scope:</h1>
    <button ng-click="i=i+1">i == {{i}}</button>
    <h1>Extension method using scope</h1>
    <button ng-click="extension()">j == {{j}}</button>
</div>