如何$编译使用新创建的作用域的AngularJS模板? [英] How to $compile an AngularJS template using a newly created scope?

查看:152
本文介绍了如何$编译使用新创建的作用域的AngularJS模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造,我想有动态使用新创建 $范围正在更新的功能弹出模式。我想要做这样的事情:

  VAR myNewScope = $ $范围新的()。
myNewScope.name ='杰克';ModalService.open(你好,{{名}}',myNewScope);

然后在我的 ModalService.open 方法,我想编译字符串,像这样的给定范围

  // ...其他服务的东西service.open =功能(模板,范围){
    VAR compiledText = $编译(模板)(范围);
    //我要compiledText =你好,杰克
}


解决方案

韦尔普......我不认为角有一个内置的方式做到这一点..所以我刚刚建立了自己的版本。

  app.controller('的TestController',函数($范围,$编译){  VAR范围= $ $范围新的()。
  scope.percentage = {值:55};
  scope.name ='杰克';  VAR味精='我们正处于{{percentage.Value}}%完成,{{名}} .. {{4/3}}';  VAR元= msg.replace(/ {{\\ S *([A-ZA-Z0-9 + - 。/ * // \\ S] *)\\ S *}} /克,函数($ 0,$ 1){
    返回范围$的eval($ 1);
  });  的console.log(元); //输出我们是在做55%,杰克.. 1.3333333333333333
});

这似乎是工作pretty以及

I am creating a pop-up modal that I want to have the capabilities of being updated dynamically using a newly created $scope. I want to do something like this:

var myNewScope = $scope.$new();
myNewScope.name = 'Jack';

ModalService.open('Hello, {{ name }}', myNewScope);

Then in my ModalService.open method I want to compile that string with the given scope like this

// ... other service stuff

service.open = function(template, scope){
    var compiledText = $compile(template)(scope);
    // I want compiledText = 'Hello, Jack'
}

解决方案

Welp... I don't think angular has a built in way to do this.. so I just built my own version.

app.controller('TestController', function($scope, $compile){

  var scope = $scope.$new();
  scope.percentage = {Value:55};
  scope.name = 'Jack';

  var msg = 'We are at {{ percentage.Value }}% done, {{ name }}.. {{ 4/3 }}';

  var element = msg.replace(/{{\s*([a-zA-Z0-9+-/*//\s.]*)\s*}}/g, function($0, $1){
    return scope.$eval($1);
  } );

  console.log(element); // prints 'We are at 55% done, Jack.. 1.3333333333333333' 
});

This seems to be working pretty well

这篇关于如何$编译使用新创建的作用域的AngularJS模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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