programing

각도에 대해 정의되지 않았거나 null입니다.JS

madecode 2023. 3. 4. 15:23
반응형

각도에 대해 정의되지 않았거나 null입니다.JS

워치 핸들링 함수를 작성할 때 newVal 파라미터를 확인합니다.undefined그리고.null왜 Angular는JS는 이러한 동작을 가지고 있지만, 특별한 유틸리티 메서드는 없는 것입니까?그래서 있다angular.isUndefined하지만 아니다angular.isUndefinedOrNull수작업으로 구현하는 것은 어렵지 않지만 각 컨트롤러에 해당 기능을 장착하기 위해 각도가 얼마나 확장됩니까?툭스

편집:

예를 들어 다음과 같습니다.

$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 maintainers에게 같은 질문을 했더니 그들은 다음과 같이 대답했습니다.!=연산자는 다음과 같이 사용할 수 있습니다.

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

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

JSHint를 사용하여 코드를 린트하는 경우 다음 설명 블록을 추가하여 대부분의 경우 자신이 무엇을 하고 있는지 알고 있음을 알려줍니다.!=나쁜 것으로 간주됩니다.

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

왜 단순히 사용하지 않는가?angular.isObject부정과 함께요?

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

@STEVER의 대답은 만족스럽다.다만, 조금 다른 어프로치를 투고하는 것이 도움이 될지도 모른다고 생각했습니다.null, defined, NaN 및 Infinity를 제외한 모든 값에 대해 true를 반환하는 isValue라는 메서드를 사용합니다.NaN에서 null과 정의되지 않은 상태로 묶는 것이 함수의 진정한 장점입니다.infinity를 null과 defined로 묶는 것은 더 논쟁의 여지가 있지만 솔직히 내 코드에는 그다지 흥미롭지 않다. 왜냐하면 나는 실제로 infinity를 사용하지 않기 때문이다.

다음 코드는 Y에서 영감을 얻은 것입니다.Lang.is Value.여기 Y의 소스가 있습니다.Lang.is Value.

/**
 * 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)));
  };
})

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

언급URL : https://stackoverflow.com/questions/17910192/undefined-or-null-for-angularjs

반응형