简体   繁体   中英

angularJS $scope variables

I have two types of variables in my $scope angularJS.

1). $scope.name, $scope.title -- these are bind to two input boxes(these are bind to UI html code).

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.

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.

Variables which are in $scope are accessible in through out(in diff functions) your controller. If you want to use those variables in another controller you can use service/factory for sharing scope variables in diff controllers.

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.

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

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?

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.

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