1

What is correct way of passing variables from web page when initializing $scope?

I currently know 2 possibilities:

  1. ng-init, which looks awful and not recommended (?)
  2. using AJAX request for resource, which requires additional request to server which I do not want.

Is there any other way?

3
  • I think option2, using ajax Commented Apr 22, 2013 at 11:19
  • It depends on your application. I my opinion both options have their use cases.
    – TheHippo
    Commented Apr 22, 2013 at 11:30
  • But is there another option? Because I don't like neither :/ Commented Apr 22, 2013 at 12:08

2 Answers 2

2

If those variables are able to be injected through ng-init, I'm assuming you have them declared in Javascript.

So you should create a service (constant) to share these variables:

var variablesFromWebPage = ...;
app.constant('initValues', variablesFromWebPage);

With this service, you don't need to add them to the scope in the app start, you can use it from any controller you have, just by injecting it (function MyCtrl(initValues) {}).

Althouhg, if you do require it to be in the scope, then this is one of the main reasons what controllers are meant for, as per the docs:

Use controllers to:

  • Set up the initial state of a scope object.
  • Add behavior to the scope object.

Just add this cotroller to your root node:

app.controller('InitCtrl', function($rootScope, initValues) {
  $rootScope.variable1 = initValue.someVariable;
  $rootScope.variable2 = initValue.anotherVariable;
});
0

@Cunha: Tnx.

Here some more details how I did it:

In the Webpage:

<script type="text/javascript">
                var variablesFromWebPage = {};
                variablesFromWebPage.phoneNumber = '@Model.PhoneNumber';
</script>

In the angular application file, registering the service:

var module= angular.module('mymodule', ['ngRoute', 'ngAnimate']);


module.factory('variablesFromWebPage', function () {
    return variablesFromWebPage
});

And then the controller:

module.controller('IndexController',

    function ($scope, $location, $http, $interval, variablesFromWebPage) {
        $scope.phoneNumber = variablesFromWebPage.phoneNumber;
    }
);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.