简体   繁体   English

angularJS $作用域变量

[英]angularJS $scope variables

I have two types of variables in my $scope angularJS. 我的$ scope angularJS中有两种类型的变量。

1). 1)。 $scope.name, $scope.title -- these are bind to two input boxes(these are bind to UI html code). $ scope.name,$ scope.title-这些绑定到两个输入框(这些绑定到UI html代码)。

2). 2)。 $scope.sum, $scope.difference -- these variables are used in JS code internally, I need them just as global variables to access in different functions. $ scope.sum,$ scope.difference-这些变量在JS代码内部使用,我需要它们像全局变量一样,以在不同的函数中访问。

Problem :- Is $scope.$watch function will run for variables of 2nd case, is these type of variables gave any bad effect on my page performance. 问题:-是$ scope。$ watch函数将针对第二种情况的变量运行,是这些类型的变量对我的页面性能产生了任何不良影响。

Variables which are in $scope are accessible in through out(in diff functions) your controller. $ scope中的变量可通过控制器的out(在diff函数中)进行访问。 If you want to use those variables in another controller you can use service/factory for sharing scope variables in diff controllers. 如果要在其他控制器中使用这些变量,则可以使用服务/工厂在diff控制器中共享作用域变量。

It's depend of your expression. 这取决于你的表情。 But, never make a watch on a expensive expression because angularjs will evaluate a number of times, and it necessarily would have a very negative impact on your application performance. 但是,永远不要看守昂贵的表达方式,因为angularjs会多次评估,并且必然会对您的应用程序性能产生非常不利的影响。

In general, it is necessary to optimize your appplication when there is a performance problem. 通常,有性能问题时有必要优化您的应用程序。 In most cases everything goes very well, and it is not desirable to unnecessarily complicate the application. 在大多数情况下,一切都进行得很好,并且不必要地不必要地使应用程序复杂化。

Also, you can use the one-way data binding , where the expression start with :: . 另外,您可以使用单向数据绑定 ,其中表达式以::开头。 The expression will stop recalculating once they are stable, after the first digest. 在第一个摘要之后,表达式一旦稳定就会停止重新计算。

If those function are not related to angular anyway you can use following Just declare a global variable in page and assign it's value to that modal 如果这些功能与角度无关,您可以使用以下命令:在页面中声明一个全局变量并将其值分配给该模态

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.globalVariable = "something";
  globalVariable = $scope.globalVariable;
});

var globalVariable;

function externalFunction(){
  alert(globalVariable);
}

Here's Plunker 这是Plunker

If those function are inside of another controller you can use service or factory to share information between controller For service and factory please refer this link 如果这些功能在另一个控制器内部,则可以使用服务或工厂在控制器之间共享信息。有关服务和工厂的信息,请参阅此链接

AngularJS : Factory and Service? AngularJS:工厂和服务?

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

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