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

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

问题描述

我有这条路线.

// 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,后者可以侦听事件并重新广播到子作用域.

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 (请参阅第一个评论)

Reference: http://www.youtube.com/watch?v=1OALSkJGsRw (see the first comment)

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

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