Angular js init ng-model from default values

This is a common mistake in new Angular applications. You don't want to write your values into your HTML on the server if you can avoid it. If fact, if you can get away from having your server render HTML entirely, all the better.

Ideally, you want to send out your Angular HTML templates, then pull down your values via $http in JSON and put them in your scope.

So if at all possible, do this:

app.controller('MyController', function($scope, $http) {
    $http.get('/getCardInfo.php', function(data) {
       $scope.card = data;
    });
});

<input type="text" ng-model="card.description" />

If you absolutely MUST render your values into your HTML from your server, you could put them in a global variable and access them with $window:

In the header of your page you'd write out:

<head>
   <script>
       window.card = { description: 'foo' };
   </script>
</head>

And then in your controller you'd get it like so:

app.controller('MyController', function($scope, $window) {
   $scope.card = $window.card;
});

I hope that helps.


If you can't rework your app to do what @blesh suggests (pull JSON data down with $http or $resource and populate $scope), you can use ng-init instead:

<input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">

See also AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Tags:

Angularjs