1

I have spent much more time than I would like to admit trying to figure this out and I cannot seem to no matter what approach I try. I have a variable being set in a .peb.html file and a corresponding angular module. Like below:

<script type="text/javascript">
    var globalVisit = {*visit*};
    var cart = {*cart*}
</script>

in the angular module I have two providers defined like below.

buyModule.service('visit', ($window) => {
    return $window.visit;
});

buyModule.service('cart', ($window) => {
    return $window.cart;
});

and a controller defined like:

buyModule.controller('BuyCtrl', ($window, $scope, visit, cart) => {
$scope.visit = visit;
$scope.cart = cart;
}));

There is much more to the file but it is irrelevant to the question. My problem is that while visit seems to be loading fine via the provider cart appears to be overwritten/loses its value in the controller. I debugged the statement and in the buyModule.service('cart', ($window) => part the $window.cart has a value set but it just disappears when I try to step through the controller. Does anyone know what I am doing wrong here for cart that is working for visit? This has been incredibly frustrating because as far as I can tell they are handled the exact same but have different results. I am using angular 1.x.

thurmc
  • 495
  • 1
  • 8
  • 29
  • did you registered cart service properly with the controller.? That may be an issue. – Viplock Oct 27 '16 at 07:32
  • That may be what I am missing but if I did not register it correctly I am not sure how I can? It appears to be registered in the same way as the visit one unless I am missing something or the registration is outside of the file? Also I should say that somehow this issue is fixed if I create an array in the peb.html file like var cart = [{id:{*cart*}}] and then access it like cart[0].id. I am so confused as to how that works but the other way doesn't – thurmc Oct 27 '16 at 07:37
  • what if you use `factory` instead like this `buyModule.factory('cart', ($window) => {`? looking at your code it seems that there's no need to use `service`, since you're returning object from the service function – Max Koretskyi Oct 27 '16 at 07:38

1 Answers1

0

Hey you are doing correct,please check script is defined before this initialization. Like:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);
Filip Cornelissen
  • 3,682
  • 3
  • 31
  • 41
Arun
  • 1,177
  • 9
  • 15
  • Refer:http://stackoverflow.com/questions/19383725/how-to-access-global-js-variable-in-angularjs-directive – Arun Oct 27 '16 at 07:39