在AngularJS指令中,将链接函数的参数传递给模板。

问题描述 投票:1回答:3

我有一个简单的指令,我想访问模板中的链接函数中的变量,如何实现?

我的指令。

app.directive("hello", function() {
  return {
    restrict: "E",
    template: '<div> '+str+' <div/>'
    link : function(scope, element, attrs) {
      var str = "hello";
    }
  }
});

这里是codepen上的一段代码。演示

javascript angularjs angularjs-directive
3个回答
2
投票

在作用域中添加变量,它们将在模板中可用。

scope.str = "hello";

而你的模板应该使用angular表达式

template: '<div>{{str}}<div/>',

所以你的指令会像

app.directive("hello", function() {
  return {
    restrict: "E",
    template: '<div>{{str}}<div/>',
    link : function(scope, element, attrs) {
      scope.str = "hello";
    }
  }
});

编辑

如果你想绑定html,使用 ngbindHtml

请看 plnkr


1
投票

有多种方法,我需要在这里向你解释,所以请考虑两边的变化需要,我的意思是你要从指令调用发送变量。

<html ng-app="app">
<body>
  <hello data-str="'I am don'"></hello>
</body>
</html>

这里的data-str是指str是一个变量,上面有 "我是唐 "的文字,就是这样。

现在

angular.module("app", []);

angular.module("app").directive("hello", function() {
  return {
    scope:{
      str:"="
    },
    restrict: "E",
    template: '<div>{{linkVar}}{{str}}<div/>',
    link : function(scope, element, attrs) {
     scope.linkVar = 'It works!' 
      console.log(scope.str);
    }
  }
});

你可以在我添加的指令对象中看到这一点。

 scope:{
          str:"="
        },  

在这里,我们决定,当指令在html中调用时,将提供 "str",而不是只提供这个,请注意。

现在

scope.linkVar = 'It works!' 

这是最重要的事情,你应该看到scope.linkVar的意思是你的javascript变量名称为str = "hello";这不是angular的方式,所以angular不会更新它的所有引用。我的意思是当你在模板中使用时。

现在希望它清楚,如果是,请告诉我。

khajaamin


0
投票

你可以用 "这个

app.directive("hello", function() {
  return {
    this.str = '';
    restrict: "E",
    template: '<div> '+this.str+' <div/>'
    link : function(scope, element, attrs) {
      this.str = "hello";
    }
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.