0

I minimized the problem to this simple reproduction. Create new Asp.net MVC app, add Angular.js via nugget.

_Layout.cshtml:

<head>
    <!-- Other stuff -->
    @RenderSection("JavascriptInHead", required: false)
</head>

_Index.cshtml

@section JavascriptInHead {   
   <script src="~/Scripts/angular.min.js"></script>
}
<div ng-app>
    {{2 + 2}}
</div>

So this works (obviously), however when I click, say About or Contact menu to reload another view and then go back to Home, I get

{{2 + 2}}

Then I click page reload two times and I get

4

Please help me understand this..

2
  • Your About and Contact views are probably MVC partial views that are out of the angular context when you navigate to them. When you refresh these pages, angular sees it as a new whole SPA application so it binds correctly on reload. Commented Dec 18, 2014 at 13:57
  • What I mean by reloading is that Home page needs to be reloaded twice in order for Angular to work. Yes these two pages are partial views. So the flow is this - Home page (works) -> About -> Home page (doesn't work, refresh once, refresh twice - works) Commented Dec 18, 2014 at 14:06

1 Answer 1

1

Angular bootstraps when the document loads. So if you are loading html that contains angular into your page without doing a full page refresh, you'll need to bootstrap angular manually. Try adding this script to your partial page:

angular.element(document).ready(function() {
  angular.bootstrap(document);
});

btw, I for one appreciate you posting a concise example rather than 100 lines of code from your actual project. If your actual project has an app name, however, like this...

<div ng-app="myApp">

then the js you put into your partial page should look like this...

angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});

Documentation for manually bootstrapping Angular can be found here: https://docs.angularjs.org/guide/bootstrap

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! So Angular wasn't bootstrapping, interesting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.