如何绑定一个指令注入服务,而不是父母或孤立的范围是什么? [英] how do i bind a directive to an injected service instead of a parent or isolated scope?

查看:184
本文介绍了如何绑定一个指令注入服务,而不是父母或孤立的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关这个问题:<一href=\"http://stackoverflow.com/questions/18774978/how-do-i-create-a-dynamic-nav-which-gets-allowed-menu-items-passed-to-it\">How做我创建一个动态导航它获取传递给它允许菜单项?

基本上,我有任何意见之外的资产净值。净资产值需要显示的菜单项用户有权访问。

Basically, I have a nav outside of any views. The nav needs to display menu items which a user has access to.

我创建像这样一个指令的导航标记:

I create the nav markup with a directive like so:

<tree family="treeFamily"></tree>

其中, treeFamily 是将用于建立导航菜单中的数据。

Where treeFamily is the data which will be used to build the navigation menu.

但是,因为我的资产净值是什么意见之外,它没有一个控制器,因此不存在所谓的作用域变量 treeFamily 。这意味着该指令没有得到任何数据来创建导航。

However, since my nav is outside of any views, it doesn't have a controller, so there is no scope variable called treeFamily. Which means the directive doesn't get any data to create a navigation.

我本来以为我可以注入的服务与菜单项中的数据,但没有办法,我可以看到告诉角度指令以使用从注入的服务获取的数据进行绑定。

I originally thought I could just inject a service with the data for the menu items, but then there is no way that I can see to tell an angular directive to use data taken from an injected service for binding.

这似乎是唯一可行的另一种方法是有一个名为treeFamily一个$ rootScope变量并生成指令的标记绑定到该网址。

The only other way that seems to be possible is to have a $rootScope variable called treeFamily and have the directive generated markup bind to that instead.

推荐答案

如果你不想在这里使用一个 $ rootScope 变量是一个稍微哈克解决方案,但你可以由该元件得到的范围。

If you don't want to use a $rootScope variable here is a slightly hacky solution but you could get the scope by the element.

例。

所以说你有一个这样的元素的数据应用到测试控制器

Say your data is applied to a test controller so you have a element like this

<div id="test" ng-controller="test">

您可以做使用jQuery这个例子中(不要求)

You could do this example using jQuery (not required)

$('#test').scope().treeFamily

有它可以访问,你需要从,正在进行演示让您的数据范围。

There it is you have access to the scope that you need to get your data from, demo in progress.

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

Demo: http://jsfiddle.net/hq26h/

在演示中的随机指令从测试控制器访问 treeFamily 数据时,该指令是外控制器。

In the demo the random directive is accessing the treeFamily data from the test controller when the directive is outside the controller.

如果您wan't您的服务数据绑定,你可以做到这一点。

If you wan't your service data to be bindable, you can do this

app.directive('something', function( $someNavDataService ) {
    return function( $scope ) {
       $scope.navData = $someNavDataService;
    }; 
});

这篇关于如何绑定一个指令注入服务,而不是父母或孤立的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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