Development Tip

AngularJS의 경우 정의되지 않거나 null

yourdevel 2020. 10. 6. 19:30
반응형

AngularJS의 경우 정의되지 않거나 null


시계 처리 함수를 작성할 때 newVal 매개 변수를 확인 undefined하고 null. AngularJS는 왜 그런 동작을하는데 특별한 유틸리티 방법이 없나요? 그래서이 angular.isUndefined아니라 angular.isUndefinedOrNull. 손으로 구현하는 것은 어렵지 않지만 각 컨트롤러에서 해당 기능을 갖도록 각도를 확장하는 방법은 무엇입니까? Tnx.

편집 :

예 :

$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);
    });
};

항상 애플리케이션에 정확히 추가 할 수 있습니다.

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

내 제안은 자신의 유틸리티 서비스를 작성하는 것입니다. 각 컨트롤러에 서비스를 포함하거나 상위 컨트롤러를 만들고 유틸리티 서비스를 범위에 할당하면 모든 하위 컨트롤러가이를 포함하지 않아도이를 상속합니다.

예 : http://plnkr.co/edit/NI7V9cLkQmEtWO36CPXy?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, Utils) {
    $scope.utils = Utils;
});

app.controller('ChildCtrl', function($scope, Utils) {
   $scope.undefined1 = Utils.isUndefinedOrNull(1);  // standard DI
   $scope.undefined2 = $scope.utils.isUndefinedOrNull(1);  // MainCtrl is parent

});

app.factory('Utils', function() {
  var service = {
     isUndefinedOrNull: function(obj) {
         return !angular.isDefined(obj) || obj===null;
     }

  }

  return service;
});

또는 rootScope에도 추가 할 수 있습니다. 고유 한 유틸리티 기능으로 각도를 확장하는 몇 가지 옵션입니다.


나는 lodash 관리자들에게 같은 질문을 했고 그들은 !=여기 에서 연산자를 사용할 수 있다고 언급하면서 대답했습니다 .

if(newVal != null) {
  // newVal is defined
}

이것은 JavaScript의 유형 강제를 사용하여 undefined또는 의 값을 확인합니다 null.

If you are using JSHint to lint your code, add the following comment blocks to tell it that you know what you are doing - most of the time != is considered bad.

/* jshint -W116 */ 
if(newVal != null) {
/* jshint +W116 */
  // newVal is defined
}

Why not simply use angular.isObject with negation? e.g.

if (!angular.isObject(obj)) {
    return;
}

@STEVER's answer is satisfactory. However, I thought it may be useful to post a slightly different approach. I use a method called isValue which returns true for all values except null, undefined, NaN, and Infinity. Lumping in NaN with null and undefined is the real benefit of the function for me. Lumping Infinity in with null and undefined is more debatable, but frankly not that interesting for my code because I practically never use Infinity.

The following code is inspired by Y.Lang.isValue. Here is the source for Y.Lang.isValue.

/**
 * A convenience method for detecting a legitimate non-null value.
 * Returns false for null/undefined/NaN/Infinity, true for other values,
 * including 0/false/''
 * @method isValue
 * @static
 * @param o The item to test.
 * @return {boolean} true if it is not null/undefined/NaN || false.
 */
angular.isValue = function(val) {
  return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
};

Or as part of a factory

.factory('lang', function () {
  return {
    /**
     * A convenience method for detecting a legitimate non-null value.
     * Returns false for null/undefined/NaN/Infinity, true for other values,
     * including 0/false/''
     * @method isValue
     * @static
     * @param o The item to test.
     * @return {boolean} true if it is not null/undefined/NaN || false.
     */
    isValue: function(val) {
      return !(val === null || !angular.isDefined(val) || (angular.isNumber(val) && !isFinite(val)));
  };
})

lodash provides a shorthand method to check if undefined or null: _.isNil(yourVariable)

참고URL : https://stackoverflow.com/questions/17910192/undefined-or-null-for-angularjs

반응형