2

I need to access to data with angularjs, as one would do with a simple static <div ng-init="data=['data']"/> in a context where the ng-init attribute has to be set from data coming from a cookie.

This pretty much should work, however, my partial making use of {{}} to access to data returns empty string.

I suspect it's a matter of race condition.

The simplified HTML code is as follows (the code is within a ng-controller):

<script>
    var data = $.cookie("data");    
    $("#data").attr("ng-init", data);
</script>

<div> Data is '{{data}}'</div>
Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95

1 Answers1

1

It looks like you're using jquery to get the cookie. Why not just use the angular $cookie service which gives you access to cookies right from within your controller. That would eliminate needing to use ng-init at all. In my experience ng-init is only useful when you need to init something that's printed out server-side.

angular.module('test', []).controller('TestCtrl', function($scope, $cookies) {
  $scope.data = $cookies.data;
});
Joe
  • 2,596
  • 2
  • 14
  • 11
  • That's one way to do the job. But I wanted not to pollute my controller scope, hence the external model. Looking at the suggested $apply – Stéphane de Luca May 20 '14 at 16:29
  • ng-init is only meant to pass variables in from the server, meaning the values would be there on the DOM before angular is bootstrapped. If you wish to use ng-init to populate based on cookies, you're going to have to do that on the server side. To be honest, I think including a whole new jquery library along with extra script tags on the page to set values is polluting your project way more than one single line in your controller. – Joe May 20 '14 at 16:36
  • Anyway, you're right. I do this. Thanks a lot Joe (btw, nice Web site shah!) – Stéphane de Luca May 20 '14 at 16:36
  • With the feedback I have now, it's clearly the right way to go @theJoeBiz, thanks a lot! – Stéphane de Luca May 20 '14 at 21:58