0

I am trying to use data I get from the server in my angular code.

To do this, I first receive the data in my HTML file with the following code:

  <script type="text/javascript">
    var __firstName= <%- JSON.stringify(givenName) %>;
  </script>

Then, I inject it in a service in my .js file:

myApp.service('user', function() {
  return givenName=function(){
    var user = __firstName;
    return user;
  };  
});

which I inject in my controller:

var myApp = angular.module('frontApp', []);

    myApp.controller('teammateInviteCtrl', ['$scope', '$element', '$http', '$window', '$log', '$timeout', 'user', function ($scope, $element, $http, $window, $log, $timeout, user) {

      $scope.account = {
        given_name: user.givenName(),
        family_name: '',
        email: '',
        password: '',
        company: '',
        phone: ''
      };

    //some code

    }]);

But here I get an empty result for $scope.account.given_name. How can I fix this?

4
  • Have you used console.log to see where the data is being lost? Commented Feb 28, 2014 at 15:50
  • the data is defined properly on the HTML file but I lose it in the js file Commented Feb 28, 2014 at 15:51
  • which js file? Do you see the data in the service before it is used in the controller? Commented Feb 28, 2014 at 15:52
  • You probably need to inject __firstName into your service. I bet that is where the data is being lost. Commented Feb 28, 2014 at 15:58

1 Answer 1

1

I recommend ng-init. Example.

 <div ng-init="user=<%- JSON.stringify(givenName) %>">

Note: I would strongly suggest to user a rest API and get the data as a JSON get from the server instead of this circus. But if you are hell bent on doing it this way, ng-init is much better solution compared to what you are trying to achieve.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.