0

i have a controller:

myApp.controller('vistaPreviaCtrl', ['$scope', '$window', 
    function ($scope, $window) {
        angular.element(document).ready(function (){
            $scope.my_var = $window.my_var; //once
        })
}]);

I want every change made in $window.my_var change in $scope.my_var too. There is a way?

avenda
  • 502
  • 1
  • 5
  • 15

1 Answers1

1

If $window.my_var is an object or array:

myApp.controller('vistaPreviaCtrl', ['$scope', '$window', function ($scope, $window) {
    $scope.my_var = $window.my_var;
}]);

$scope.my_var will point to the same object referenced by $window.my_var, so they are already inherently "linked".

If $window.my_var is a primitive (e.g. number, string), you need to use a watch to update the local $scope's value.:

myApp.controller('vistaPreviaCtrl', ['$scope', '$window', function ($scope, $window) {
    $scope.$watch('$window.my_var', function (newVal) {
        $scope.my_var = newVal;
    });
}]);

I also recommend reading more about references and values in JavaScript: https://stackoverflow.com/a/6605700/2943490.

Community
  • 1
  • 1
user2943490
  • 6,900
  • 2
  • 22
  • 38
  • Using and storing values outside the Angular life-cycle is not a good idea and will only lead to much frustration. If you are trying to share data it is best to use Services, Factories, or Providers. – Enzey Nov 24 '14 at 23:53