函数绑定在2个指令之间不起作用

时间:2015-07-08 18:08:39

标签: angularjs data-binding angularjs-directive

我正在尝试将函数绑定到指令。这是我的小提琴代码:

var myApp = angular.module('myApp', []);

myApp.directive("myFoo", function () {
    return {
        restrict: "E",
        scope: {
            callback: '&'  
        },
        template: '<span ng-click="callback()">MyFoo</span>'
    };
});

myApp.directive("myBar", function () {
    return {
        restrict: "E",       
        template: '<div>MyBar > <my-foo test="cb"></my-foo></div>',
        link: function (scope) {
            scope.cb = function (x) {console.log('click');}    
        }
    };
});

DEMO

我必须做一些愚蠢的事情,因为当我点击my-foo元素时回调不起作用。有什么建议为什么这个例子不起作用?

1 个答案:

答案 0 :(得分:1)

您需要将其传递给您正在使用的回调属性,并将其直接与&#39; =&#39;:

相关联
var myApp = angular.module('myApp', []);

myApp.directive("myFoo", function () {
    return {
        restrict: "E",
        scope: {
            callback: '='  
        },
        template: '<span ng-click="callback()">MyFoo</span>'
    };
});

myApp.directive("myBar", function () {
    return {
        restrict: "E",       
        template: '<div>MyBar > <my-foo callback="cb"></my-foo></div>',
        link: function (scope) {
            scope.cb = function (x) {console.log('click');}    
        }
    };
});

jsFiddle:http://jsfiddle.net/xohv1syq/

jsFiddle使用&amp ;: http://jsfiddle.net/hzxcptzv/