Does angular.equals () work like an angular expression?

I am trying to display a div if the object is not empty. Using this answer, I am trying to use angular.equals to check for emptiness, but does not work as expected

 var test = angular.module('test',[]); test.controller('testCtrl', ['$scope', function($scope){ $scope.foo={}; $scope.bar="bam" }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="test"> <div ng-controller="testCtrl"> <div ng-show="!angular.equals(foo,{})">{{bar}}</div> </div> </div> 

The bar value is only expected to show if foo not equal to an empty object. However, foo explicitly set to {} , and bar is still shown.

+5
source share
4 answers

If you want to access an angular object from templates or expressions, you must make it available in the area where you want to use it. In this case, you can put it in the testCtrl area.

 var test = angular.module('test',[]); test.controller('testCtrl', ['$scope', function($scope){ $scope.angular = angular; $scope.foo={}; $scope.bar="bam" }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="test"> <div ng-controller="testCtrl"> <div ng-show="!angular.equals(foo,{})">{{bar}}</div> </div> </div> 

I usually put utility objects on $rootScope , so they are available everywhere.

+8
source

A cleaner way is to add the angular equals method to the $ scope:

 var test = angular.module('test',[]); test.controller('testCtrl', ['$scope', function($scope){ $scope.angularEquals = angular.equals; } 

Then you can use the equals method in the template, for example:

 <div ng-show="!angularEquals(foo,{})">{{bar}}</div> 
+6
source

Your view is looking for a function in scope, and $scope.angular.equals does not exist. You need to write one like this:

 var test = angular.module('test', []); test.controller('testCtrl', ['$scope', function($scope) { $scope.foo = {}; $scope.bar = "bam"; $scope.isEmpty = function(obj) { return angular.equals(obj,{}); }; } ]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="test"> <div ng-controller="testCtrl"> <div ng-hide="isEmpty(foo)">{{bar}}</div> </div> </div> 
+4
source

Angular functions cannot be used inline, AFAIK. You can perform an equal check using the function inside the controller and return the result.

-1
source

Source: https://habr.com/ru/post/1206880/


All Articles