angularjs with oop inheritance in action

后端 未结 3 1687
终归单人心
终归单人心 2020-12-07 08:31

Abstract

I\'m working on an application that uses angular as a client side framework, angular currently rocks and I\'m really happy using it, though now I find tha

3条回答
  •  攒了一身酷
    2020-12-07 09:02

    Your guesses sounds perfectly applicable.

    You can reuse functionality defined in parent controllers by simply calling methods attached to the parent scope:

    HTML

    JavaScript

    function ParentCtrl($scope) {
        $scope.parentMethod = function () {
            //method body
        };
    }
    
    function ChildCtrl($scope) {
        $scope.childMethod = function () {
            //functionality
            $scope.parentMethod();
            //functionality
        };
    }
    

    If you want to use the JavaScript approach with prototype inheritance you can use:

    var myApp = angular.module('myApp',[]);
    
    function Parent($scope) {
        $scope.name = 'Superhero';    
    
        $scope.clickParent = function() {
            $scope.name = 'Clicked from base controller';
        }    
    }
    
    function Child($scope, $injector) {
    
        debugger;
        $injector.invoke(Parent, this, {$scope: $scope});
    
        $scope.name = 'Superhero Child';
    
        $scope.clickChild = function(){
            $scope.clickParent();
        }       
    }
    Child.prototype = Object.create(Parent.prototype);
    

    http://jsfiddle.net/mhevery/u6s88/12/

    For services, for example, you can use:

    (function () {
    
    function ParentService(arg1) {
       this.arg1 = arg1;
    }
    
    function ChildService(arg1, arg2) {
       ParentService.call(this, arg1);
       this.arg2 = arg2;
    }
    
    ChildService.prototype = new ParentService();
    
    app.service('ChildService', ChildService);
    
    }());
    

    Also check this discussion and the blog post about inheritance in AngularJS I posted.

提交回复
热议问题