AngularJS-在回调中包含变量

AngularJS - Include variable in a callback

本文关键字:包含 变量 回调 AngularJS-      更新时间:2023-09-26

我有一个角度指令,它允许以以下方式传递回调:

angular
    .module('app')
    .directive('myDirective', myDirective);
function myDirective() {
    return {
        bindToController: {
            buttonClick: '&'
        },
        controller: 'MyController',
        controllerAs: 'vm',
        restrict: 'E',
        scope: {},
        templateUrl: '<div><button data-ng-click="vm.buttonClick(''hello'')">Click me</button>'
    };
}

然后在我的父HTML中,我有

<my-directive button-click="ctrl.myCallback()"></my-directive>

最后在我的父控制器中,我有

function myCallback(msg) {
    alert('message is: ' + msg);
}

目标是显示"hello"或传递给回调的任何数据,但这不起作用。

我做错什么了吗?当没有指定参数时,它可以工作

感谢

仅供参考,这里有Plunker的链接(http://plnkr.co/edit/F6TafMWD3EWqVCCLaMys?p=preview)

使用&时,需要调用带有1个参数的函数,该参数是要传递的参数的映射。

<my-directive button-click="ctrl.myCallback(msg})"></my-directive>
return {
    //...
    template: '<div><button data-ng-click="vm.buttonClick({msg: ''hello''})">Click me</button>'
}

如果你的函数有两个参数,你会得到:

<my-directive button-click="ctrl.myCallback(msg1, msg2})"></my-directive>
return {
    //...
    template: '<div><button data-ng-click="vm.buttonClick({msg1: ''hello'', msg2: '''there''})">Click me</button>'
}
function myCallback(msg1, msg2) {
    alert('message is: ' + msg1 + ' ' + msg2);
}

该GIST在指令绑定方面非常详尽:https://gist.github.com/CMCDragonkai/6282750

看看点8

另一个好的资源是:https://thinkster.io/egghead/isolate-scope-am

更新:我更新并修复了你的plunkr:http://plnkr.co/edit/W4RnZeCaxfCbVcYeKXLD?p=preview

  • 请小心选择角度版本1.x
  • 如果使用bindToController,则指令控制器必须是一个函数。空函数可以
  • 仔细看看我是如何命名用于调用myCallback的变量的,并将其与第二个plunkr进行比较:http://plnkr.co/edit/OvCXC0jeycIOxyoQ0R9w?p=preview如果你需要更多关于这一点的解释,请告诉我

看看这个例子。将$compile用于绑定事件范围

var app = angular.module('app', []);
app.controller('MyController', function($scope){
    $scope.buttonClick = function(msg ){
      console.log(msg);
       $scope.msg = msg;
    };
}).directive('directive', function($compile) {
    return {
        restrict : 'E',
        link : function(scope, element){
            
                var content = $compile('<div><button type="button" ng-click="buttonClick(' + "'Test Msg'" + ')">Click me</button> {{msg}}')(scope);
                element.append(content);
            
        }
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyController">
   <directive></directive>
</div>