简体   繁体   English

为什么角度多次调用函数

[英]Why angular called function multiple times

I have following part of code. 我有以下部分代码。

 var app = angular.module('app', []); app.controller('DemoCtrl', function($scope, accessService) { $scope.isPageAccessible = function(pageCode) { return accessService.checkAccess(pageCode); }; }); app.factory('accessService', function(){ var availableRoles = ['PROFILE']; var service = {}; service.checkAccess = function (role) { console.log('Check role: ' + role); return availableRoles.some(function (element) { return element == role; }); }; return service; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <ul class="nav nav-tabs" ng-app="app" ng-controller="DemoCtrl"> <li class="active"><a href="#">Home</a></li> <li><a ng-show="isPageAccessible('PROFILE')" href="#">Profile</a></li> <li><a ng-show="isPageAccessible('MESSAGE')" href="#">Messages</a></li> </ul> 

And I surprised why angular call function isPageAccessible() multiple times. 我很奇怪为什么多次调用角度函数isPageAccessible()。 In my mind function isPageAccessible() should be called only twice, but in the concole I see 4 calling. 在我看来,isPageAccessible()函数应该仅被调用两次,但是在conconle中,我看到了4次调用。 If somebody know why? 如果有人知道为什么?

it's happens because of two-way data binding in angular. 发生这种情况的原因是在角度上存在双向数据绑定 to solve such problem I did following: use one-way data binding. 为了解决这种问题,我做了以下工作:使用单向数据绑定。

 var app = angular.module('app', []); app.controller('DemoCtrl', function($scope, accessService) { $scope.isProfile = accessService.checkAccess('PROFILE'); $scope.isMessage= accessService.checkAccess('MESSAGE'); }); app.factory('accessService', function(){ var availableRoles = ['PROFILE']; var service = {}; service.checkAccess = function (role) { console.log('Check role: ' + role); return availableRoles.some(function (element) { return element == role; }); }; return service; }); 
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <ul class="nav nav-tabs" ng-app="app" ng-controller="DemoCtrl"> <li class="active"><a href="#">Home</a></li> <li ng-if="::isProfile"><a href="#">Profile</a></li> <li ng-if="::isMessage"><a href="#">Messages</a></li> </ul> 

From version 1.3 I can use one-way data binding. 从1.3版开始,我可以使用单向数据绑定。 Here is only tiny thing for me - it's not working with functions and I have to move roles into controller. 这对我来说只是一件小事-它无法使用功能,因此我必须将角色移至控制器中。

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

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