2014-09-22 2 views
0

У меня есть следующий код ...Использование прототипа для расширения контроллера в Угловое

var app = angular.module('plunker', []); 
TestController = function ($scope, $interval) { 
    $scope.test = this; 
    $scope.name = 'World'; 
    this.init(); 
    $interval(function() { 
     //Added this because we shouldn't update until we either get the user data or that request fails 
     $scope.test.init(); 
    }, 500); 
}; 
TestController.prototype.init = function() { 
    console.log("Test this thing"); 
}; 
app.controller('MainCtrl', TestController); 

Это прекрасно работает, но теперь мне нужно, чтобы включить функцию инициализации в другой контроллер, так что я хочу, и наследовать от общего прототипа , Тем не менее, когда я пытаюсь выполнить this, это не работает.

Каков правильный способ справиться с подобными вещами в JS?

+0

в plunker у вас есть 'функция TimeBox', но в прототипе попробуйте назначить' Test Controller.prototype = new Test() ' – Grundy

+0

Спасибо, что у меня все еще есть такая же проблема. – Jackie

+1

все работают, если вы определяете всю функцию в файле' app.js' или добавляете ссылку на 'test.js' в' index.html' – Grundy

ответ

2

Это машинопись пример http://plnkr.co/edit/HOeJ7nkkp2qRl53zEvVj?p=preview

Машинопись:

class Controller { 
    static $inject = ['$scope']; // deps 

    constructor($scope) { 
    $scope.vm = this; 
    } 

    value(): string { 
    return '123'; 
    } 
} 

class NewController extends Controller { 
    constructor($scope) { 
    super($scope); 
    } 

    value(): string { 
    return super.value() + '456'; 
    } 
} 

declare var angular: any; 
angular.module('my', []).controller('controller', NewController); 

В JavaScript это выглядит следующим образом:

//Compiled TypeScript 

var __extends = this.__extends || function (d, b) { 
    function __() { this.constructor = d; } 
    __.prototype = b.prototype; 
    d.prototype = new __(); 
} 

var Controller = (function() { 
    function Controller($scope) { 
     $scope.vm = this; 
    } 
    Controller.$inject = [ 
     '$scope' 
    ]; 
    Controller.prototype.value = function() { 
     return '123'; 
    }; 
    return Controller; 
})(); 

var NewController = (function (_super) { 
    __extends(NewController, _super); 
    function NewController($scope) { 
     _super.call(this, $scope); 
    } 
    NewController.prototype.value = function() { 
     return _super.prototype.value.call(this) + '456'; 
    }; 
    return NewController; 
})(Controller); 

angular.module('my', []).controller('controller', NewController); 

Если вам нужно ООП в JavaScript использовать л как http://prototypejs.org/

+0

Я посмотрю, что вы опубликовали и проверите после того, как я получу шанс переварить спасибо! – Jackie

Смежные вопросы