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!

1

1 Answer 1

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"
   ...
 });

}]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.