2

I'm learning Angular JS coming from a Java background. I've written my first module and I'd like to extend it- from my (beginner) perspective it looks like a Class which can be extended. So I've coded the following which includes two modules: myApp and myApp2.

Angular JS Code:

var myApp = angular.module('myApp', []);

myApp.controller('UserCtrl', ['$scope', function ($scope) {

    $scope.name="cat";
    $scope.type="pet";

}]);

var myApp2 = angular.module('myApp2', ['myApp']);

myApp2.controller('UserCtrl', ['$scope', function ($scope) {

    $scope.name="dog";

}]);

HTML Code

<body ng-app="myApp2">

    <div ng-controller="UserCtrl">

        <p>{{ name }}</p>
        <p>{{ type }}</p>
    </div>

In the above example, myApp2 "type" evaluates to "". Is it possible to inherit properties and methods from MyApp?

Thanks!

ElChiniNet
  • 2,778
  • 2
  • 19
  • 27
user2824073
  • 2,407
  • 10
  • 39
  • 73
  • Possible duplicated: [Can an AngularJS controller inherit from another contoller in the same module?](http://stackoverflow.com/questions/18461263/can-an-angularjs-controller-inherit-from-another-contoller-in-the-same-module) – Beterraba Feb 27 '14 at 10:45

1 Answers1

2

It is easier to extend controllers. In the example below, CatCtrl inherits the AnimalCtrl scope:

<div ng-controller="AnimalCtrl">
    <p>{{ animal.name }}</p>
    <p>{{ animal.type }}</p>

   <div ng-controller="CatCtrl">
       <p>{{ animal.race }}</p>
   </div>
</div>

myApp.controller('AnimalCtrl', ['$scope', function ($scope) {

 $scope.animal = {
   gender: "M",
   type: ""
   ...
 };

}]);

myApp.controller('CatCtrl', ['$scope', function ($scope) {

 angular.extend($scope.animal, {
   type: "Cat",
   race: "Albino"
   ...
 });

}]);
asgoth
  • 35,552
  • 12
  • 89
  • 98