Marius Grigaitis
Marius Grigaitis

Reputation: 2520

Passing variables to angular.js scope from web page

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?

Upvotes: 1

Views: 2907

Answers (2)

yonexbat
yonexbat

Reputation: 3012

@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;
    }
);

Upvotes: 0

Caio Cunha
Caio Cunha

Reputation: 23394

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;
});

Upvotes: 2

Related Questions