[英]What to use instead of angular scope functions?
我不喜欢角度范围功能 - 他们没有明确的合同。 它们将参数放在范围内的某个位置,并将其结果放在某个范围内,而不是显式地将参数作为函数参数并return
结果。 举个例子( plunkr ):
HTML
<html ng-app="exampleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="myctrl.js"></script>
</head>
<body ng-controller="MyCtrl">
Here is my params:
<input type="number" ng-model="first"> + <input type="number" ng-model="second">
<button ng-click="sum()">Sum it!</button>
<p>{{result}}</p>
</body>
</html>
JS
//myctrl.js
var app = angular.module('exampleApp', []);
app.controller('MyCtrl', function($scope) {
$scope.sum = function() {
$scope.result = $scope.first + $scope.second;
}
});
一旦函数变得大于10行,理解它的主要结果应该是很棘手的。 另外我不明白如何用jsdoc记录它。 是否有更好的角度功能的最佳实践?
PS这里的例子有点合成,大多数时候我的函数会询问角度服务的东西并转换结果进行显示。
PPS很多人建议使用controller as
语法,但我认为它不能完全解决问题,函数仍然不能具有返回值,它所做的一切都隐藏在副作用中。
您可以使用controller as
代替$scope
。
<body ng-controller="MyCtrl as ctrl">
<body ng-controller="MyCtrl as ctrl">
Here is my params:
<input type="number" ng-model="ctrl.first"> + <input type="number" ng-model="ctrl.second">
<button ng-click="ctrl.sum()">Sum it!</button>
<p>{{ctrl.result}}</p>
</body>
在JS
//myctrl.js
var app = angular.module('exampleApp', []);
app.controller('MyCtrl', function() {
var vm = this;
vm.sum = function() {
vm.result = vm.first + vm.second;
}
});
是的,将所有内容附加到作用域对象可能很麻烦,因为依赖性变得不清楚并且实现变得更长。 另一种方法是将控制器作为对象发布到作用域中,并使用controller as
将视图直接绑定到它controller as
语法:
function MyCtrl() {
this.first = 0;
this.second = 0;
this.result = 0;
}
MyCtrl.prototype.sum = function () {
this.result = this.first + this.second;
}
angular.module('example', []).controller('MyCtrl', MyCtrl);
<body ng-controller="MyCtrl as ctrl">
Here is my params:
<input type="number" ng-model="ctrl.first"> + <input type="number" ng-model="ctrl.second">
<button ng-click="ctrl.sum()">Sum it!</button>
<p>{{ ctrl.result }}</p>
</body>
请参阅https://docs.angularjs.org/api/ng/directive/ngController#example 。
据“ 角样式指南发表在GitHub上”,你应该使用的controllerAs
在经典控制器与语法$scope
语法。
原因#1 :控制器被构造,“新近”并提供单个新实例,并且controllerAs语法比经典$ scope语法更接近JavaScript构造函数的语法。
原因#2 :它促进了对视图中“点”对象的绑定的使用(例如,customer.name而不是name),这更加符合上下文,更易于阅读,并且避免了在没有“点”的情况下可能出现的任何参考问题。
原因#3 :帮助避免在具有嵌套控制器的Views中使用$ parent调用。
<!-- avoid -->
<div ng-controller="CustomerController">
{{ name }}
</div>
<!-- recommended -->
<div ng-controller="CustomerController as customer">
{{ customer.name }}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.