解析angular指令中的作用域变量

Resolving scope variables in an angular directive

本文关键字:作用域 变量 angular 指令 解析      更新时间:2023-09-26

我正在创建一个角指令(元素),将应用一些转换文本。

指令如下:

module.directive('myDir', function() {
    return {
      restrict: 'E',
      link: function(scope, elem, attrs) {
        console.log(elem.text());       
      },
    };
  });

现在我只是在那里放置了一个console.log,以确保我看到了预期的文本。

如果我的html是这样的,它会像预期的那样工作:

<my-dir>Hello World!</my-dir>

但是,如果我使用一个来自作用域的变量,例如:

<my-dir>{{myMessage}}</my-dir>

那么这就是我在控制台输出中看到的文本,而不是变量值。我想我明白为什么输出是这样的,但我不知道如何得到正确的值。要求是该指令应该能够转换两个示例中的文本。

想法吗?

使用$interpolate服务将字符串转换为函数,并将作用域作为参数应用以获得值(fiddle):

module.directive('myDir', function($interpolate) {
    return {
      restrict: 'E',
      link: function(scope, elem, attrs) {
        console.log($interpolate(elem.text())(scope));
      },
    };
  });

如果您真的有兴趣获取插入的内容,那么请使用$interpolate服务对插入的内容进行评估。

link: function(scope, elem, attrs) {
    console.log($interpolate(elem.text())(scope));
},

不要忘记添加$interpolate作为依赖于指令函数。

看看$compile或http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx

这个应该可以工作:

module.directive('myDir', function($compile) {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      console.log($compile(elem.text())(scope));       
    },
  };
});

我建议你在指令上使用一个隔离的作用域,它可以让你访问值,而不必从dom中获取它。您还可以在

作用域的link函数中直接操作它。
<my-dir my-message="myMessage"></my-dir>

JS

module.directive('myDir', function() {
    return {
      restrict: 'E',
      template: '{{myMessage}}',
      scope:{
        myMessage: '=', 
      },
      link: function(scope, elem, attrs) {
        console.log(scope.myMessage);       
      },
    };
});