从ng-include中的ng-click更改ng-include的内容我想要更改

时间:2014-07-26 18:49:30

标签: angularjs

我有一个模板设置,顶部有导航,导航链接如下:

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

这些链接改变了ng-include元素的内容:

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

这很好用,但是在我将部分加载到ng-include之后添加了一个链接:

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

对ng-include部分没有影响。我希望能够从元素中更改此元素的内容。知道我做错了吗?

1 个答案:

答案 0 :(得分:4)

ngInclude创建子范围,因为subPage是基本类型(字符串),subPage='views/customers/jobs.html'将更新子范围的subPage属性,但{父范围内的{1}}将不受影响。

这可能类似于你现在所拥有的,链接不起作用......

subPage

Live Demo

有两种方法可以解决这个问题。一个是使用<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> ...

$parent

Live Demo

另一种是绑定到一个对象而不是一个像字符串一样的原语......

<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

有关详细信息,请查看this answer on prototypal inheritance in Angular