簡體   English   中英

使用什么而不是角度范圍功能?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM