简体   繁体   English

angular.equals()是否可以作为角度表达式使用?

[英]Does angular.equals() work as an angular expressions?

I'm trying to display a div if an object is non-empty. 如果对象非空,我正在尝试显示div。 Using this answer, Im trying to use angular.equals to check emptyness, but its not behaving as expected 使用这个答案,我试图使用angular.equals来检查angular.equals ,但它的行为不符合预期

 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 expectation here is that the value of bar will only show if foo is not equal to an empty object. 这里的期望是bar的值只会显示foo是否不等于空对象。 However, foo is clearly set to {} and yet bar still shows. 但是, foo显然设置为{}但仍然显示bar

If you want to access the angular object from templates or expressions, you have to make it available on the scope of where you want to use it. 如果要从模板或表达式访问angular对象,则必须在要使用它的范围内使其可用。 In this case you can put it on the testCtrl 's scope. 在这种情况下,您可以将它放在testCtrl的范围内。

 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 generally put utility objects on $rootScope , so they're available from everywhere. 我通常将实用程序对象放在$rootScope ,因此它们可以在任何地方使用。

A cleaner way would be to only add the angular equals method to the $scope: 更简洁的方法是只将angular equals方法添加到$ 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, like: 然后你可以在模板中使用equals方法,例如:

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

Your view is looking for a function on the scope, and $scope.angular.equals does not exist. 您的视图正在查找范围上的函数,并且$scope.angular.equals不存在。 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> 

Angular functions can't be used inline, AFAIK. 角度函数不能用于内联,AFAIK。 You could do the equal check with a function inside the controller instead and return the result. 您可以使用控制器内部的函数进行相等的检查,然后返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM