當我編寫手錶處理函數時,我檢查undefined
和null
上的newVal參數。爲什麼AngularJS有這樣的行爲,但沒有特定的效用方法?所以有angular.isUndefined
但不是angular.isUndefinedOrNull
。手工實現並不困難,但是如何在每個控制器中擴展角度以實現該功能? TNX。未定義或爲AngularJS爲空
編輯:
的例子:
$scope.$watch("model", function(newVal) {
if (angular.isUndefined(newVal) || newVal == null) return;
// do somethings with newVal
}
它是普遍接受的做法來處理這樣的方式?
編輯2:
的例子的jsfiddle(http://jsfiddle.net/ubA9r/):
<div ng-app="App">
<div ng-controller="MainCtrl">
<select ng-model="model" ng-options="m for m in models">
<option value="" class="ng-binding">Choose model</option>
</select>
{{model}}
</div>
</div>
var app = angular.module("App", []);
var MainCtrl = function($scope) {
$scope.models = ['Apple', 'Banana'];
$scope.$watch("model", function(newVal) {
console.log(newVal);
});
};
你可以切換到CoffeeScript的。有一個questionmark postifix運算符可以做到這一點。 –
當你需要這樣的功能時,你能否給出真實的案例? –
爲什麼不[失去未定義的檢查](http://stackoverflow.com/a/15992131/188246),只檢查'newVal == null'? –