如何在不创建新范围的情况下将一个部分包含到另一个中? [英] How to include one partial into other without creating a new scope?

查看:24
本文介绍了如何在不创建新范围的情况下将一个部分包含到另一个中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这条路线.

// index.html
<div ng-controller="mainCtrl">
    <a href='#/one'>One</a>
    <a href='#/two'>Two</a>
</div>​​​​​​​​​
<div ng-view></div>

这就是我将部分加载到我的 ng-view 中的方式.

And this is how I'm loading the partials into my ng-view.

// app.js
​var App = angular.module('app', []);​​​​​​​
App.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/one', {template: 'partials/one.html', controller: App.oneCtrl});
    $routeProvider.when('/two', {template: 'partials/two.html', controller: App.twoCtrl});
  }]);

当我点击链接时,它会在 ng-view 中显示相应的标记.但是当我尝试使用 ng-includepartials/one.html 中包含 partials/two.html 时,它会正确显示,但会创建一个不同的范围,所以我无法与之交互.

When I click the links, it shows me the appropriate markup inside the ng-view. But when I try to include partials/two.html inside partials/one.html using ng-include, it shows it properly but creates a different scope so I'm not able to interact with it.

// partials/two.html - markup
<div ng-controller="twoCtrl">I'm a heading of Two</div>

// partials/one.html - markup
<div ng-controller="oneCtrl">I'm a heading of One</div>
<div ng-include src="'partials/two.html'"></div>

我该如何解决这个问题?或者有没有其他方法可以达到同样的效果?

​ How do I resolve this problem? Or Is there any other way to achieve the same result?

推荐答案

您实际上可以在不使用共享服务的情况下执行此操作.$scope.$emit(...) 可以将事件分派给 $rootScope,$rootScope 可以监听它们并重新广播到子作用域.

You can actually do this without using a shared service. $scope.$emit(...) can dispatch events to the $rootScope, which can listen for them and rebroadcast to the child scopes.

演示:http://jsfiddle.net/VxafF/

参考:http://www.youtube.com/watch?v=1OALSkJGsRw(见第一个评论)

这篇关于如何在不创建新范围的情况下将一个部分包含到另一个中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆