Phương thức isUndefined() trong AngularJS về cơ bản kiểm tra xem một tham chiếu (reference) có được định nghĩa hay không. Phương thức này trả về True nếu tham chiếu truyền vào hàm không được định nghĩa hoặc là undefined, ngược lại trả về False.
Cú pháp
angular.isUndefined(value)
Ví dụ – Kiểm tra tham chiếu có undefined hay không
Tạo file "isUndefined.html" trong thư mục dự án Angular và dán đoạn mã sau:
<!DOCTYPE html>
<html>
<head>
<title>angular.isUndefined()</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">
</script>
</head>
<body ng-app="app" style="text-align:center">
<h1 style="color:green">
Welcome to Tutorials Point
</h1>
<h2>AngularJS | angular.isUndefined()</h2>
<div ng-controller="example">
<b>Name: {{name}}</b>
<br><br>
{{isUndefined}}
<br><br>
<b>Name: {{name2}}</b>
<br><br>
{{isUndefined1}}
</div>
<!-- Script kiểm tra giá trị -->
<script>
var app = angular.module("app", []);
app.controller('example', ['$scope', function ($scope) {
// Định nghĩa key & value
$scope.name = "SIMPLY LEARNING";
$scope.name2; // chưa gán giá trị -> undefined
$scope.isUndefined = angular.isUndefined($scope.name) == true
? "$scope.name is Undefined."
: "$scope.name is Defined.";
$scope.isUndefined1 = angular.isUndefined($scope.name2) == true
? "$scope.name2 is Undefined."
: "$scope.name2 is Defined.";
}]);
</script>
</body>
</html>
Kết quả đầu ra
Chạy file HTML như bình thường. Trên trình duyệt sẽ hiển thị:
- $scope.name đã được định nghĩa → "Defined."
- $scope.name2 chưa gán giá trị → "Undefined."