使用 angularJS 1.3,在下面的代码中,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.20/angular.js"></script>
<script type="text/javascript">
var app = angular.module("sample", []);
app.controller("emp", function(){
this.Name = "jag";
this.sal = "4500";
this.getAnnualSal = function(){
return (this.sal) * 12;
}
});
</script>
</head>
<body ng-app="sample">
<div ng-controller="emp as o">
Hello {{o.Name}}, your annual salary is {{o.getAnnualSal()}}
</div>
</body>
</html>
将 function(getAnnualSal
) 保留为 Controller 实例成员看起来很奇怪。
因为,emp
的每个 Controller 实例都有自己的 getAnnualSal
。
emp
Controller 实例范围如下所示:
将函数(getAnnualSal
)维护为原型(prototype)成员是否有意义?如果是,请提供语法。
最佳答案
您的替代方法是将 Controller 声明为单独的类。 AngularJS 没有为此提供特殊语法,因此您可以...
function MyController() {
this.Name = "jag";
this.sal = "4500";
}
MyController.prototype.getAnnualSal = function(){
return (this.sal) * 12;
}
var app = angular.module("sample", []);
app.controller("emp", MyController);
如果您想使用自定义注入(inject)(例如 $scope
、$rootScope
...),您可以:
function MyController($scope) { ... all the former code ... }
...
var app = angular.module("sample", []);
app.controller("emp", ['$scope', MyController]);
有关注入(inject)的疑问,请引用官方教程或文档(例如$provide
)。唯一的区别是使用匿名函数或命名函数(始终充当构造函数)。
关于javascript - 如何避免函数作为 Controller 范围内的实例成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36067726/