AngularJS:使用控制器中的模板更新视图?

时间:2013-06-28 14:14:40

标签: angularjs angularjs-scope

我一直在使用路由,我已经看到了如何使用路由和视图模板更新ng-view。但我遇到的问题是我正在进行REST调用并取决于我从响应我希望使用视图模板更新部分DOM,但我不想涉及路由。

有谁知道我怎么做到这一点?或者任何例子都很棒

提前致谢

2 个答案:

答案 0 :(得分:1)

另一个答案。根据您在评论中的描述,听起来您希望有条件地显示部分DOM。

当您想要有条件地显示部分DOM时,您有以下选择:

使用ng-showng-hide指令。
根据RESTful调用的返回值,您可以设置一个模型来识别需要显示的DOM。一个例子:

<div ng-show="status">
    This text will be shown only when the status is truthy
</div>
<div ng-hide="status">
    This text will be shown only when the status is false.
</div>

在控制器内部,您可以根据RESTful调用将status设置为true或false,并根据RESTful调用后希望显示的DOM部分。

您可以使用ng-switch指令
虽然ng-showng-hide指令会有条件地显示DOM的内容,但任何人都可以只打开源文件并查看两者的内容,ng-switch指令只会加载内容基于哪种情况满足了swtich。一个例子:

<div ng-switch on="status">
    <div ng-switch-when="true">
        This text will be shown only when the status is truthy.
        Else this is completely hidden and cannot be seen even 
        when looking at the source.
    </div>
    <div ng-switch-when="false">
        This text will be shown only when the status is false.
        Else this is completely hidden and cannot be seen even 
        when looking at the source.
    </div>
</div>

当状态为真时显示第一个子div,否则根本不显示。优于ng-showng-hide的优点是,如果未满足案例,DOM将不包含子元素。

答案 1 :(得分:0)

$location.path()可以在这里使用。

因此,在您的父控制器中,您可以进行REST调用。一旦掌握了数据,就可以决定采用哪条路线。路由值进入path()函数。

举个例子,让我们说如果您的REST调用返回樱桃,您需要采用/foo路径(基于您的$routeProvider将加载与该路由关联的模板) 。然后,您可以编写以下内容:

$location.path('/foo');

它将加载/ foo路径 - $routeProvider然后将负责加载与该路径关联的模板。

参考:$location