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

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

问题描述

当我写的腕表处理功能我检查的newval参数不确定。为什么AngularJS有这样的行为,但不具有特别的实用性的方法?因此,有 angular.isUndefined 而不是 angular.isUndefinedOrNull 。不难实现,通过手,但如何角延伸到在每个控制器的功能? TNX。

修改

这个例子:

  $范围。$表(样板,功能(的newval){
    如果(angular.isUndefined(的newval)||的newval == NULL)回报;
    //使用的newval做出头
}

它是共同接受的做法来处理这​​样的方式?

编辑2

本的jsfiddle例子( http://jsfiddle.net/ubA9r/ ):

 < D​​IV NG-应用=应用程序>
  < D​​IV NG控制器=MainCtrl>
      <选择NG模型=模式NG选项=M在模型M>
          <期权价值=级=NG结合>选择模型< /选项>
      < /选择>
      {{模型}}
  < / DIV>
< / DIV>VAR应用= angular.module(应用程序,[]);VAR MainCtrl =功能($范围){
    $ scope.models = ['苹果','香蕉'];
    $范围。$表(样板,功能(的newval){
        的console.log(的newval);
    });
};


解决方案

您可以随时添加它究竟是为您的应用

  angular.isUndefinedOrNull =功能(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天全站免登陆