brian
brian

Reputation: 2775

The most Angular-y way of pre-loading data into $scope

Portions of my application are full AJAX and some are traditional POST and reload. Getting data into $scope is a trivial task using $http, but, what about when data is available to a template during the page load (in the normal MVC way everybody knows and loves) instead of via AJAX after the fact?

Consider the following piece of code:

<div ng-repeat="address in addresses">
  {{ address.address1 }}
  {{ address.city }}, {{ address.state }} {{ address.zip }}
</div>

How would I go about loading 100 dynamically generated addresses into $scope.addresses without using AJAX?

Upvotes: 1

Views: 91

Answers (2)

Borys Generalov
Borys Generalov

Reputation: 2345

Easiest way would be to use ng-init for your "inline" controller:

@model SampleViewModel
...
<div ng-controller="SampleCtrl" ng-init="[email protected]">

Another approach is demonstrated here:

<script>
  function SampleCtrl($scope){
     $scope.adresses = @Html.Raw(Json.Encode(Model));
      ...
  }
</script>

<div ng-controller="SampleCtrl" ng-repeat="address in addresses">

Upvotes: 2

Prateek Jain
Prateek Jain

Reputation: 1552

ng-init is an option by angularJS to operate on data while page loading.

Here, in your case you can implement a function and then assign those dynamic generated values into $scope.addresses.

<div ng-init="functionToAssignAddresses()">

 /* Populate your Addresses here.*/   

</div>

for more information you can follow documentation here for ng-init.

Upvotes: 0

Related Questions