AngularJS - 如何以编程方式创建一个新的、隔离的范围? [英] AngularJS - How can I create a new, isolated scope programmatically?

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

问题描述

我想用 Angular.factory 创建一个 AlertFactory.我定义了一个像follow

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);

那么,我如何将隔离范围从控制器传递到工厂?我在控制器中使用跟随代码

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

AlertFactory.open($scope);

但是 $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);

这里的关键是将 true 传递给 $new,它接受 isolate 的一个参数,从而避免从父级继承作用域.

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

可在以下位置找到更多信息:http://docs.angularjs.org/api/ng.$ro​​otScope.范围#$new

More information can be found at: http://docs.angularjs.org/api/ng.$rootScope.Scope#$new

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

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