source

개체에 속성이 있는지 확인합니다.

goodcode 2023. 2. 14. 23:06
반응형

개체에 속성이 있는지 확인합니다.

객체가 AngularJS에서 특정 속성을 가지고 있는지 확인하려면 어떻게 해야 합니까?

hasOwnProperty'를 사용하여 객체에 특정 속성이 있는지 확인할 수 있습니다.

if($scope.test.hasOwnProperty('bye')){
  // do this   
}else{
  // do this then
}

여기 jsFiddle 데모가 있습니다.

도움이 되길 바랍니다.

if('bye' in $scope.test) {}
else {}

문제는 디렉티브를 링크할 때뿐만 아니라 $http로 로드될 수 있다는 것입니다.

조언은 다음과 같습니다.

controller: function($scope) {
  $scope.$watch('test.hello', function(nv){ 
     if (!nv) return; 
     // nv has the value of test.hello. You can do whatever you want and this code
     // would be called each time value of 'hello' change
  });
}

또는 값이 1개만 할당되어 있는 것을 알고 있는 경우:

controller: function($scope) {
  var removeWatcher = $scope.$watch('test.hello', function(nv){ 
     if (!nv) return; 
     // nv has the value of test.hello. You can do whatever you want
     removeWatcher();
  });
}

이 코드는 'test'의 워처 값을 삭제합니다.hello'가 할당되었습니다(컨트롤러, 에이잭스 등).

언급URL : https://stackoverflow.com/questions/20464807/check-if-an-object-has-a-property

반응형