AngularJS指令回调

nak*_*kor 17 angularjs angularjs-directive

我想通过标签上的参数将调用发送回指令,然后在指令内适当时调用该方法.例如,单击按钮时,请在父控制器上调用方法.

我有一个简单的plunker它无法正常工作

html文件:

<body ng-controller="ParentController">
    <h1> Method Arguments </h1>
    <h3> open console to view output</h3>
    <hello-world onLoadCallback="myCallback(arg1)"></hello-world>
</body>
Run Code Online (Sandbox Code Playgroud)

javascript文件:

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

function ParentController($scope) {
  $scope.myCallback = function(var1){
    console.log("myCallback", var1);
  }
}
app.directive('helloWorld', function() {
  return {
      restrict: 'AE',
      template: '<h3>Hello World!!</h3>',
      scope:{
            onLoadCallback: '&'
        },
        link: function(scope, element, attrs, dateTimeController) {
            console.log('linked directive, not calling callback')
            scope.onLoadCallback('wtf');

      }
  };
});
Run Code Online (Sandbox Code Playgroud)

nak*_*kor 39

棘手棘手的角度,当在HTML中声明参数时,它需要使用snake case,而不是camelcase来匹配.

作品:

<hello-world on-load-callback="myCallback(arg1)"></hello-world>
Run Code Online (Sandbox Code Playgroud)

不起作用:

<hello-world onLoadCallback="myCallback(arg1)"></hello-world>
Run Code Online (Sandbox Code Playgroud)

  • 我认为Angular开发人员并没有因此而失败. (27认同)

use*_*062 25

回调也需要是:

scope.onLoadCallback({arg1: 'wtf'});
Run Code Online (Sandbox Code Playgroud)

然后将命名参数绑定到回调属性中使用的相应参数(并非所有参数都需要使用).