AngularJS – 如何以编程方式创build一个新的,隔离的作用域?

我想用Angular.factory创build一个AlertFactory。 我如下定义了一个html模板

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

标题由呼叫控制器提供并应用如下

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

那么,我怎样才能把控制器的隔离范围传给工厂呢? 我正在使用控制器跟踪代码

 AlertFactory.open($scope); 

但$ scope是全局控制器范围variables。 我只是想通过一个只有标题属性的工厂小范围。

谢谢。

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

你可以从$rootScope创build一个新的作用域,如果你注入的话,或者只是从你的控制器作用域 – 这不应该因为你将它隔离。

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

这里的关键是传递给$new ,它接受isolate一个参数,这避免了inheritance父类的范围。

有关更多信息,请访问: http : //docs.angularjs.org/api/ng.$ro​​otScope.Scope#$new

如果你只需要插入内容,使用$ interpolate服务而不是$ compile,那么你将不需要一个范围:

 myApp.factory('myService', function($interpolate) { var template = "<h1>{{title}}</h1>"; var interpolateFn = $interpolate(template); return { open: function(title) { var html = interpolateFn({ title: title }); console.log(html); // append the html somewhere } } }); 

testing控制器:

 function MyCtrl($scope, myService) { myService.open('The Title'); } 

小提琴

以下是步骤:

  1. 使用var comiledHTML = angular.element(yourHTML);将您的HTML添加到DOM var comiledHTML = angular.element(yourHTML);
  2. 创build一个新的范围,如果你想var newScope = $rootScope.$new();
  3. 调用$ comile(); 返回链接函数的函数var linkFun = $compile(comiledHTML);
  4. 通过调用linkFun绑定新的作用域var finalTemplate = linkFun(newScope);
  5. 将finalTemplate附加到您的DOM YourHTMLElemet.append(finalTemplate);

看看我的plunkr。 我正在编程生成一个渲染指令的部件指令。

https://plnkr.co/edit/5T642U9AiPr6fJthbVpD?p=preview

 angular .module('app', []) .controller('mainCtrl', $scope => $scope.x = 'test') .directive('widget', widget) .directive('render', render) function widget() { return { template: '<div><input ng-model="stuff"/>I say {{stuff}}</div>' } } function render($compile) { return { template: '<button ng-click="add()">{{name}}</button><hr/>', link: linkFn } function linkFn(scope, elem, attr) { scope.name = 'Add Widget'; scope.add = () => { const newScope = scope.$new(true); newScope.export = (data) => alert(data); const templ = '<div>' + '<widget></widget>' + '<button ng-click="export(this.stuff)">Export</button>' + '</div>'; const compiledTempl = $compile(templ)(newScope); elem.append(compiledTempl); } } } 

我假设你在谈论隔离范围时,你正在谈论一个指令。

这是一个如何做的例子。 http://jsfiddle.net/rgaskill/PYhGb/

 var app = angular.module('test',[]); app.controller('TestCtrl', function ($scope) { $scope.val = 'World'; }); app.factory('AlertFactory', function () { return { doWork: function(scope) { scope.title = 'Fun'; //scope.title = scope.val; //notice val doesn't exist in this scope } }; }); app.controller('DirCtrl', function ($scope, AlertFactory) { AlertFactory.doWork($scope); }); app.directive('titleVal',function () { return { template: '<h1>Hello {{title}}</h1>', restrict: 'E', controller: 'DirCtrl', scope: { title: '=' }, link: function() { } }; }); 

基本上,将控制器连接到已定义隔离范围的指令。 注入到指令控制器的作用域将是一个隔离作用域。 在指令控制器中,您可以注入您的AlertFactory,以便您可以将隔离范围传递给。