AngularJS 的未定义或空值 [英] Undefined or null for AngularJS

查看:27
本文介绍了AngularJS 的未定义或空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编写手表处理函数时,我会检查 undefinednull 上的 newVal 参数.为什么 AngularJS 有这样的行为,但没有特定的实用方法?所以有 angular.isUndefined 但没有 angular.isUndefinedOrNull.手动实现它并不难,但是如何扩展 angular 以在每个控制器中具有该功能?Tnx.

编辑:

例子:

$scope.$watch("model", function(newVal) {if (angular.isUndefined(newVal) || newVal == null) 返回;//用 newVal 做一些事情}

处理这种方式是普遍接受的做法吗?

编辑 2:

JSFiddle 示例(http://jsfiddle.net/ubA9r/):

<div ng-controller="MainCtrl"><select ng-model="model" ng-options="m for m in models"><option value="" class="ng-binding">选择模型</option></选择>{{模型}}

var app = angular.module("App", []);var MainCtrl = function($scope) {$scope.models = ['苹果', '香蕉'];$scope.$watch("model", function(newVal) {控制台日志(新值);});};

解决方案

您总是可以完全为您的应用程序添加它

angular.isUndefinedOrNull = function(val) {返回 angular.isUndefined(val) ||val === 空}

When I write watch handling functions I check newVal param on undefined and null. Why does AngularJS have such a behavior, but doesn't have particular utility method? So there is angular.isUndefined but not angular.isUndefinedOrNull. It isn't hard to implement that by hand but how extend angular to have that function in each controller? Tnx.

Edit:

The example:

$scope.$watch("model", function(newVal) {
    if (angular.isUndefined(newVal) || newVal == null) return;
    // do somethings with newVal
}

Is it common accepted practice to handle such a way?

Edit 2:

The JSFiddle example (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);
    });
};

解决方案

You can always add it exactly for your application

angular.isUndefinedOrNull = function(val) {
    return angular.isUndefined(val) || val === null 
}

这篇关于AngularJS 的未定义或空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆