<!-- template.html -->
<div ng-if="items.length > 0">
<!-- content -->
</div>
vs
<!-- template.html -->
<div ng-if="$ctrt.hasItems()">
<!-- content -->
</div>
<!-- controller.js -->
$ctrt.hasItems = (itmesList) => {
return items.length > 0
};
which way is better, doing the evaluation in javascript or in the HTML template?
The second example will run the function multiple times. I think it's because angular doesn't know if any $scope
value has changed during each digest cycle. So the function will get executed for each digest cycles. In your case, it will get executed when the ng-if
conditions become true.
Here is a demo that would replicate this behaviour:
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.items = [1, 2, 3]; var x = 0; $scope.hasItems = function() { x++; console.log("execution", x); return $scope.items.length > 0; } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> Test: <div ng-if="hasItems()">Has items</div> </div>
It's always better to populate the variable in the controller, rather than check for that variable's value with any get method / function. So use your first case, where you check it directly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.