扩展angularJS模块

时间:2014-02-27 10:42:32

标签: angularjs extends

我正在学习来自Java背景的Angular JS。我已经编写了我的第一个模块,我想扩展它 - 从我的(初学者)角度来看,它看起来像Class,可以扩展。所以我编写了以下代码,其中包括两个模块:myAppmyApp2

Angular JS代码:

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代码

<body ng-app="myApp2">

    <div ng-controller="UserCtrl">

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

在上面的示例中,myApp2“type”的计算结果为“”。是否可以从MyApp继承属性和方法?

谢谢!

1 个答案:

答案 0 :(得分:1)

扩展控制器更容易。在下面的示例中,CatCtrl继承了AnimalCtrl范围:

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

}]);