当我编写观察处理函数时,我会检查
undefined
和null
的newVal参数。为什么AngularJS有这样的行为,但没有特定的实用方法呢?所以有angular.isUndefined
但没有angular.isUndefinedOrNull
。手动实现不难,但如何扩展angular使每个控制器都拥有该功能呢?谢谢。$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);
});
};
newVal == null
? - David SherretnewVal === null
将会是 false,但是newVal == null
将会是 true。David 是正确的。 - Patrick McElhaney