0

I am using ocLazyLoad library to lazy load angular javascript/html files and inject them to my module like this code snippet:

    $routeProvider.when('/Home/Index', {
        templateUrl: '/app/Index.html',
        controller: 'IndexController',
        resolve: {
            deps: [
                '$ocLazyLoad', function ($ocLazyLoad) {
                    return $ocLazyLoad.load({}, {
                        name: 'mix',
                        files: [
                            '/app/IndexController.js'
                        ]
                    });
                }
            ]
        }
    });

With this approach I get static html file from file system. But what i want is set templateUrl:'/Home/Index' so Index action method in Home controller gets executed and razor renders specified .cshtml page then return html with angular directives.

Here is what i want to do. Razor view:

<p>
    @foreach (var item in new List<int> { 1, 2, 3, 4, 5 })
    {
        @item
    }
</p>

<div ng-controller="IndexController as vm">
    <p>{{vm.text}}</p>
    <p>{{3 + 3}}</p>
</div>

Response from server:

<p>12345</p>
<div ng-controller="IndexController as vm">
    <p>{{vm.text}}</p>
    <p>{{3 + 3}}</p>
</div>

Along with this html, lazy loaded IndexController.js Then angular will do its job.

Is it possible to do that?

kadir
  • 1
  • 2

1 Answers1

0

Yes, it is possible to do that. All you need to do is remember the basics. Angular knows nothing of your server-side unless your expose it.

$routeProvider.when('/ng-Home/Index', { //It can't be the same as the Action URL since it won't work the way you want it to.
    templateUrl: '/Home/Index', //Add the html of your static page into the razor view.
    controller: 'IndexController'
    }
});

Internally, angular will call from the server side either a plain HTML file or HTML outputted from a server (an HTML response, as opposed to JSON or XML). Angular doesn't care if it's a file or response HTML. Routing will simply take the response HTML and output it.

Normally this could get messy, since not all Razor generated HTML will be compliant with the angular way of handling models. But it can help you achieve some handy things, like using bundling and minification from ASP.NET. Or adding a partial view directly into your HTML.

In your Razor view, you could add your JS files the following way:

@Scripts.Render("~/Path/To/Script")

Hope it helps!

Carlos Jimenez Bermudez
  • 1,070
  • 1
  • 14
  • 36