AngularJS-将配置参数传递给指令

AngularJS - Passing configuration parameters to a directive

本文关键字:指令 参数传递 配置 AngularJS-      更新时间:2023-09-26

我想将参数(值和函数(传递给Angular指令。

我觉得Angular中存在这样的东西,但我找不到。也许我没有使用正确的搜索术语或术语。。。

示例

<my-directive my-param="55" some-title="My title" click-callback="myOnClickCallback">
</my-directive>

这可行吗?

你不必像其他答案那样为指令创建一个私有作用域。这取决于你想对指令做什么。

您可以简单地为指令创建一个私有作用域,查看其他答案,或者使用链接中的attr,或者如果您想共享父作用域,则可以编译函数。

 link: function(scope, element, attrs) {
      attrs.myParam === 55;
      attrs.someTitle === "My Title";
      attrs.clickCallback === myOnClickCallback;
    }

我举了你问题的一个例子,作为示范

如果你对指令作用域中的"@"answers"="有疑问,请检查这个答案并阅读有角度的文档。

这里有一个工作演示,向您展示如何做到这一点。

app.directive('myDirective', function(){
  return {
    replace: true,
    scope : {
      myParam : '@',
      someTitle : '@',
      clickCallback: '&'
    },
    link: link,
    template: '<p>{{someTitle}}</p>'
  }

  function link(scope, elem, attrs){
    elem.bind('click', function(){
      scope.clickCallback();
    }) 
    console.log(scope.myParam);
    console.log(scope.someTitle);
  }
})

因此,使用"@"(传递字符串时(和"&"将数据传递到指令作用域功能。

&将允许您在原始范围内传递回调并执行它们。

你可以阅读更多关于棱角分明的文档。

指令中有三个不同的选项

你想要使用的两个是

"&"将允许您传入一个函数

"@"将接受字符串

一些毫无价值的东西,camelCase属性将被angular自动解析,并在分配值时变成camelCase(注意hypen(

.directive("myDialog", function() {
    return {
        restrict: "E", // allows us to restrict it to just elements ie <my-dialog>
        scope: {
            "close": "&onClose", // putting a new name here allows us to reference it different on the html
            // would become <my-dialog on-close="someFn()"></my-dialog>
            "myParam": "@"
        },
        template: "<button type='button' data-ng-click='close()'>Dummy - {{myParam}}</button>"
      };
});

.controller("fooCtrl", [function(){
    var vm = this;
    vm.someRandomFunction = function(){
        alert("yay!");
    };
}]);

最后的html看起来像

<div ng-controller="fooCtrl as vm">
    <my-dialog on-close="vm.someRandomFunction()" my-param="55"></my-dialog>
</div>

沃斯阅读以及答案上的链接

Plnkr

只要尝试一下,你就会从属性中获得值

链接:

function(scope, element, attrs) {
    alert(attrs.myParam);
},
    .directive('myPane', function() {
      return {
        require: '^myTabs',
        restrict: 'E',
        transclude: true,
        scope: {
        /*
        *Exmaple:
        <my-directive my-param="55" some-title="My title" click-callback="myOnClickCallback">
</my-directive>
         */
          myParam: '@',//@ is a string parameter 
          someTitle:'@',
         /*is a double direction parameter 
         *(changable in the directive itself)
         *You can pass by '=' objects and functions(with parameters)
         */
          clickCallback:'=' 
        },
        link: function(scope, element, attrs) {
          //Here you write functions of the directive and manipulate it's scope
        },
        templateUrl: 'template.html'
      };
    });

有关详细信息:https://docs.angularjs.org/api/ng/directive/ngClass.

祝你好运!