将方法从父指令传递给子指令

时间:2015-05-01 20:52:52

标签: angularjs angularjs-directive

我想从控制器传递方法 - >父指令 - >儿童指令。我通过传递参数从子控制器调用此方法。它在父指令中工作,但我无法从子指令传递参数。以下是代码:

http://jsfiddle.net/gurukashyap/e14ff06p/6/

从父指令我在控制台中获得以下响应: 'Ctrl方法123'

来自儿童指令: Ctrl方法未定义。

任何帮助表示感谢。

<div ng-app="MyApp">
    <div ng-controller="MyController">
        <container data-method="foo(value)"/>
    </div>
</div>

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

myApp.directive('container', function () {
    return {
        restrict: 'E',
        replace: 'true',
        scope: {
            methodToCall: '&method'
        },
        template: "<div>" +
            "<button ng-click='finish()'>Parent directive</button><child data-method=\"methodToCall(val) \"></child>" +
            "</div>",
        link: function (scope, element, attrs) {
            scope.paragraphs = [];
            scope.pushText = function () {
                scope.paragraphs.push(scope.textToPush);
                scope.textToPush = "";
            }
            scope.finish = function () {
                scope.methodToCall({value: '123'});                                
            }
        }
    }
});

myApp.directive('child', function () {
    return {
        restrict: 'E',
        scope : {
            methodToCall : '&method'
        },
        template : '<button ng-click = "newMethod()">Child directive </button>',
        controller : function($scope) {
        $scope.newMethod = function () {
          console.log('Test child '+$scope);
            //debugger;
        $scope.methodToCall({val : 'Testchild'});
    }
     }
    }
});

myApp.controller('MyController', function ($scope, $window) {

    $scope.foo = function (textArray) {
        console.log('Ctrl method '+textArray)
    };
});

0 个答案:

没有答案