Quinn Wilson
Quinn Wilson

Reputation: 8233

angularjs and existing markup

I'm using AngularJs in an Asp.net MVC project. I am familiar with the programming model where I let the page load and then angular calls out to a svc endpoint to retrieve some data.

That's fine but when I'm rendering the page in Asp.net MVC I have access to all of that data and I'd like to avoid the svc call.

I could have for example

<ul>
     <li data-ng-repeat="image in Images">{data}
         <button data-ng-click="delete()">x</button>
     </li>
</ul>

This would give me a new scope for each <li/> and when someone clicks on the button delete() gets a $scope containing image

If I instead wanted to bind the data in the MVC view something like :

<ul>
     @foreach (var image in Model.Images
     {
     <li>
         @image.data
         <button data-ng-click="delete()">x</button>
     </li>
     }
</ul>

What would I do to tell AngularJS about the state of the object? i.e. when the button gets pressed it would want to know about the

Am I going about this the wrong way?

Thoughts?

Upvotes: 0

Views: 96

Answers (2)

Anthony Chu
Anthony Chu

Reputation: 37530

You can serialize the initial data as JSON and embed it into the page. Something like this...

Controller

var serializer = new JavaScriptSerializer();
viewModel.ImagesJson = serializer.Serializer(images);
return View(viewModel);

Razor

app.value("images", @Html.Raw(Model.ImagesJson));

app.controller("myController", function ($scope, images) {
    $scope.images = images;
    $scope.delete = function (image) {
        // ...
    };
});

This outputs as something like this:

app.value("images", [{ "src": "/foo.jpg" }, ... ]);

Then just use Angular databinding...

<ul>
     <li data-ng-repeat="image in images">{data}
         <button data-ng-click="delete(image)">x</button>
     </li>
</ul>

Upvotes: 1

Amir Popovich
Amir Popovich

Reputation: 29846

Doing the second way isn't right since you are not using angular's data-binding but just using plain razor for rendering your view.

The "razor" rendering occurs on server side while angular's data binding happens on the client end.

You generally need to hand angular your model, and it will data bind you view to the model.

You technically can do stuff like you wrote here using $compile(read more) but that isn't right.

Upvotes: 1

Related Questions