AngularJS - 如何编程方式创建一个新的,孤立的范围是什么? [英] AngularJS - How can I create a new, isolated scope programmatically?

查看:130
本文介绍了AngularJS - 如何编程方式创建一个新的,孤立的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Angular.factory AlertFactory。
我定义HTML模板像后续

I want to create an AlertFactory with Angular.factory. I defined an html template like follow

var template = "<h1>{{title}}</h1>";

标题是通过调用控制器提供如下应用

Title is provided by calling controller and applied as follow

var compiled = $compile(template)(scope);
body.append(compiled);

那么,如何从控制器通过隔离范围的工厂?
我使用的控制器后续code

So, how I can pass isolated scope from controller to factory? I'm using in controller follow code

AlertFactory.open($scope);

不过$范围是全球性控制器范围变量。我只是想通过工厂的小范围只有title属性。

But $scope is global controller scope variable. I just want pass a small scope for factory with just title property.

感谢您。

推荐答案

您可以手动创建一个新的范围。

You can create a new scope manually.

您可以创建 $ rootScope 新的范围,如果你注入,或者只是从你的控制器范围 - 这不应该的问题,你会使其孤立

You can create a new scope from $rootScope if you inject it, or just from your controller scope - this shouldn't matter as you'll be making it isolated.

var alertScope = $scope.$new(true);
alertScope.title = 'Hello';

AlertFactory.open(alertScope);

这里的关键是通过真正 $新的,它接受一个参数为隔离,从而避免了从父继承范围。

The key here is passing true to $new, which accepts one parameter for isolate, which avoids inheriting scope from the parent.

更多信息,请访问:
<一href=\"http://docs.angularjs.org/api/ng.%24rootScope.Scope#%24new\">http://docs.angularjs.org/api/ng.$rootScope.Scope#$new

这篇关于AngularJS - 如何编程方式创建一个新的,孤立的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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