ASP.NET MVC Partial View in an AngularJS directive

AndreiC picture AndreiC · May 13, 2014 · Viewed 9.2k times · Source

I'm currently working on an ASP.NET MVC project to which some AngularJS was added - including some AngularJS directives. I need to add to an AngularJS directive a MVC partial view. Obviously,

@Html.Partial("_PartialView", {{name}}) 

doesn't work.

So far all my searches online provided no help.

Any idea how I could render a partial view inside an Angular directive?

Thanks!

Answer

JPRO picture JPRO · May 13, 2014

Angular exists strictly on the client side whereas MVC views exist on the server side. These two cannot interact directly. However, you could create an endpoint in which your partial view is returned as HTML. Angular could call this endpoint, retrieve the HTML, and then include it inside a directive.

Something like this:

app.directive("specialView", function($http) {
  return {
    link: function(scope, element) {
      $http.get("/views/partials/special-view") // immediately call to retrieve partial
        .success(function(data) {
          element.html(data);  // replace insides of this element with response
        });
    }  
  };
});