我正在学习 Angular JS
,有 Java 背景。我已经编写了我的第一个模块,我想扩展它 - 从我(初学者)的 Angular 来看,它看起来像一个可以扩展的Class
。因此,我编写了以下代码,其中包括两个模块:myApp
和 myApp2
。
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
继承属性和方法?
谢谢!
最佳答案
扩展 Controller 更容易。在下面的示例中,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"
...
});
}]);
关于angularjs - 扩展 angularJS 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22066049/