0

I have a template setup with a navigation at the top and the navigation links are like:

<a href="" ng-click="subPage='views/customers/jobs.html'">Jobs</a>

And those links change what is inside of an ng-include element:

<section data-ng-include="subPage" ng-init="subPage='views/customers/information.html'" ng-animate></section>

This works well, however after I load a partial into the ng-include putting a link like:

<a href="" ng-click="subPage='views/customers/jobs.html'">Jobs</a>

has no effect on the ng-include section. I want to be able to change the content of this element from within the element. Any idea what I'm doing wrong?

jdgower
  • 1,172
  • 15
  • 18

1 Answers1

4

ngInclude creates a child scope, and because subPage is a primitive type (a string), subPage='views/customers/jobs.html' will update the subPage property of the child scope, but subPage on the parent scope will be unaffected.

This is probably similar to what you have right now, the links don't work...

<div ng-app ng-init="subPage = 'foo.html'">
    <div ng-include="subPage"></div>
    <script type="text/ng-template" id="foo.html">
        <div><h1>foo</h1>
            <a href="" ng-click="subPage='bar.html'">bar</a >
        </div>
    </script>
    <script type="text/ng-template" id="bar.html">
        <div><h1>bar</h1>
            <a href="" ng-click="subPage='foo.html'">foo</a >
        </div>
    </script>
</div>

Live Demo

There are two ways to solve this. One is to use $parent...

<div ng-app ng-init="subPage = 'foo.html'">
    <div ng-include="subPage"></div>
    <script type="text/ng-template" id="foo.html">
        <div><h1>foo</h1>
            <a href="" ng-click="$parent.subPage='bar.html'">bar</a >
        </div>
    </script>
    <script type="text/ng-template" id="bar.html">
        <div><h1>bar</h1>
            <a href="" ng-click="$parent.subPage='foo.html'">foo</a >
        </div>
    </script>
</div>

Live Demo

The other is to bind to an object instead of a primitive like a string...

<div ng-app ng-init="subPage.url = 'foo.html'">
    <div ng-include="subPage.url"></div>
    <script type="text/ng-template" id="foo.html">
        <div><h1>foo</h1>
            <a href="" ng-click="subPage.url='bar.html'">bar</a >
        </div>
    </script>
    <script type="text/ng-template" id="bar.html">
        <div><h1>bar</h1>
            <a href="" ng-click="subPage.url='foo.html'">foo</a >
        </div>
    </script>
</div>

Live Demo

For more information, check out this answer on prototypal inheritance in Angular.

Community
  • 1
  • 1
Anthony Chu
  • 37,170
  • 10
  • 81
  • 71