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


80

시계 처리 함수를 작성할 때 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);
    });
};

1
coffeescript로 전환 할 수 있습니다. 이를 수행하는 물음표 postifix 연산자가 있습니다.
— Patryk Ziemkowski 2013

이러한 기능이 필요할 때 실제 사례를 알려주시겠습니까?
— Stepan Suvorov 2013

3
정의되지 않은 검사를 잃어 버리고 그냥 검사 하지 않는 이유는 무엇 newVal == null입니까?
— David Sherret 2014

3
newVal이 정의되지 않은 경우 (newVal === null)은 false를 반환하기 때문입니다.
— Greg Dougherty 2015

예, newVal === null거짓이지만 newVal == null사실입니다. 데이비드가 맞습니다.
— Patrick McElhaney

답변:


160

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

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

js 라이브러리를 이러한 방식으로 확장하는 것이 항상 좋은 것은 아니지만 내 검색에 매우 가깝다는 것을 알고 있습니다. 사실 나는 왜 그것에 집착했는지 더 관심이 있습니다. 감시 핸들러에서 undefined 및 null을 처리하는 것이 표준 관행입니까?
— slo2ols

음, IMHO, 좋은 구조의 응용 프로그램에서는 그러한 경우가 없어야합니다.
— Stepan Suvorov

알겠습니다. 하지만 여전히 'null'은 올바른 선택의 결과이며 '정의되지 않음'과 구별되어야한다고 생각합니다.
— Stepan Suvorov

24
@STEVER 잘 구조화 된 응용 프로그램에서 'null'이 나쁜 이유는 무엇입니까? 예를 들어, 사용자가 로그인 할 때만 변수를 사용자 데이터로 채워야하는 경우 로그인 전과 로그 아웃 후에 null이 적절한 값입니다.
— RonLugge 2014

17

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

예 : 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에도 추가 할 수 있습니다. 사용자 고유의 유틸리티 기능으로 각도를 확장하기위한 몇 가지 옵션입니다.


4
나는 강하게 유틸리티 기능이 DI하지한다고 생각
— slo2ols

@ slo2ols는 서비스를 만들 수 있습니다를 캡슐화 만 루에 주입
— lucuma

14

나는 lodash 메인테이너들에게 똑같은 질문을 했고 그들은 !=여기 에서 연산자를 사용할 수 있다고 언급하면서 대답했다 .

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

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

JSHint를 사용하여 코드를 린트하는 경우 다음 주석 블록을 추가하여 수행중인 작업을 알고 있음을 알리십시오. 대부분의 경우 !=나쁜 것으로 간주됩니다.

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

9

단순히 angular.isObject부정과 함께 사용하지 않는 이유는 무엇 입니까? 예

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

...하지만 값의 유형을 알고 angular.isX일치 하는 방법을 선택할 수있는 경우 훌륭한 옵션 입니다.
— Phasmal

null개체입니다
— spicykimchi apr

로부터 isObject반환 : 문서 진정한 경우 value입니다 Object하지만 null.
— DerMike

7

@STEVER의 대답은 만족 스럽습니다. 그러나 약간 다른 접근 방식을 게시하는 것이 유용 할 것이라고 생각했습니다. null, undefined, NaN 및 Infinity를 제외한 모든 값에 대해 true를 반환하는 isValue라는 메서드를 사용합니다. null 및 undefined를 사용하여 NaN을 럼핑하는 것은 나에게 함수의 진정한 이점입니다. 무한대를 null 및 undefined로 묶는 것은 더 논쟁의 여지가 있지만 실제로 Infinity를 사용하지 않기 때문에 솔직히 내 코드에는별로 흥미롭지 않습니다.

다음 코드는 Y.Lang.isValue에서 영감을 받았습니다 . 다음은 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)));
};

또는 공장의 일부로

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

왜 val === null || !angular.isDefined(val)그냥으로 바꾸지 val == null않습니까?
— J. Steve 2017 년

3

lodash 는 정의되지 않았는지 또는 null인지 확인하는 간단한 방법을 제공합니다. _.isNil(yourVariable)

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.