【问题标题】:Passing attribute value to directive controller将属性值传递给指令控制器
【发布时间】:2016-04-07 15:33:25
【问题描述】:

指令用法

<my-directive my-attr='StackOverflow'></my-directive>

指令定义

app.directive('myDirective', function($scope){
  return {
    restrict: 'E',
    template: 'I want to print the attribute value',
    controller: function($scope){
      // I also want to access the attribute value here.
    }
  };
});

有没有办法做到这一点。

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    而不是scope: true写,

    scope: {
      myattr: '@'
    }
    

    然后myattr 将在$scope 中可用

    Fiddle

    确保使用小号的套管,不知何故,使用任何其他套管,如帕斯卡或骆驼会导致问题。

    【讨论】:

      【解决方案2】:

      是的,您可以使用作用域将值传递给指令。

      你的代码可以写成类似

         app.directive('myDirective', function($scope){
          return {
            restrict: 'E',
            Scope:{
              myAttr:'='
            },
            template: 'I want to print the attribute value: and here is your value: {{myAttr}}',
            controller: function($scope){
             // I also want to access the attribute value here.
              console.log($scope.myAttr);
            }
      

      }; });

      和用法一样

      <my-directive my-attr='StackOverflow'></my-directive>
      

      这是同样的问题 Angularjs - Pass argument to directive

      您还可以在以下位置找到有关指令用法的更多信息 https://docs.angularjs.org/guide/directive

      【讨论】:

      • 类似的代码对我有用,我不知道是什么导致了问题。
      • 你能提供小提琴吗!
      猜你喜欢
      • 1970-01-01
      • 2015-10-27
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多