【问题标题】:Extending angularJS modules扩展 angularJS 模块
【发布时间】:2014-03-30 17:40:58
【问题描述】:

我正在学习 Angular JS 来自 Java 背景。我已经编写了我的第一个模块,我想扩展它——从我(初学者)的角度来看,它看起来像一个可以扩展的 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的属性和方法?

谢谢!

【问题讨论】:

标签: angularjs extends


【解决方案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"
   ...
 });

}]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多