0

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.

aditya
  • 149
  • 1
  • 3
  • 15

3 Answers3

0

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.

Aravinder
  • 503
  • 4
  • 8
0

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.

Paul Boutes
  • 3,285
  • 2
  • 19
  • 22
  • I moved some pages from jQuery plateform to angular plateform and combined more than 10 pages functionality wise on single page, one of my ng-repeat creates 150 watches per iteration, so this is necessary, when array.length = 100 there are 15000 watches approx. which is creating problem?? – aditya Jul 31 '15 at 12:29
  • In fact, the ng-repeat directive of AngularJS is getting slow above 2500 two-way data bindings – Paul Boutes Jul 31 '15 at 12:40
  • Then what should we do in case of large and complex pages having large number of watches and data bindings. – aditya Jul 31 '15 at 13:15
  • You can use pagination, one-way data binding, avoid inline method into ngRepeat directive. There is a good article here : [Improve performance](http://tech.small-improvements.com/2013/09/10/angularjs-performance-with-large-lists/) – Paul Boutes Jul 31 '15 at 13:28
0

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?

Community
  • 1
  • 1
blue
  • 932
  • 7
  • 9