0

我有一个带有控制器的父指令,它在 $scope 上设置一个方法。

然后,在子指令中,我尝试通过&.

但是,ng-click内部子指令不会与父范围函数一起触发。我做错了吗?

父指令(定义方法的地方)

app.directive('ParentDirective', [
    '$http',
    function($http) {
        return {
            restrict: 'AE',
            template: '' +
                '<div child-directive ' +
                    'list="list" ' +
                '/>' +
            '',
            controller: function ($scope, $http) {

                $scope.setSelected = function (selector) {
                    console.log('hit!', selector);
                }

                $scope.list = [];

            },
            link: function postLink(scope, element, attrs) {}
        };
    }
]);

子指令(尝试在 ng-click 上调用父方法,但不起作用)

app.directive('childDirective', [

        '$window',
        function($window) {
            return {
                restrict: 'AE',
                scope: {
                    setSelected: '&',
                    list: '=',
                },
                template: '' +
                    '<ul>' +
                        '<li ng-repeat="person in list" ng-click="setSelected(person)">{{person.uri}}</li>' +
                    '</ul>' +
                '',
                link: function postLink(scope, element, attrs) {
                }
            };
        }
    ]);

我是否$scope.setSelected()从父级错误地传递到子级指令?

编辑:所以我改变了父模板来分配这样的功能:模板:''+''+'',

这现在将触发函数,但参数不会从子指令传递。如何让子指令将参数传递给父指令函数?

4

1 回答 1

1

ParentDirective 有错字应该是:parentDirective

在 parentDirective 模板中,您应该传递函数 'list="list" ' + 'set-selected="setSelected(person)"'

尝试这个:

html:

<parent-directive ></parent-directive>

js:

app.directive('parentDirective', [
    '$http',
    function($http) {
        return {
            restrict: 'AE',
            template: '' +
                '<div child-directive ' +
                    'list="list" ' + 'set-selected="setSelected(person)"'+
                '/>' +
            '',
            controller: function ($scope, $http) {

                $scope.setSelected = function (selector) {
                    console.log('hit!', selector);
                }

                $scope.list = [];

            },
            link: function postLink(scope, element, attrs) {}
        };
    }
])
  app.directive('childDirective', [

        '$window',
        function($window) {
            return {
                restrict: 'AE',
                scope: {
                    setSelected: '&',
                    list: '=',
                },
                template: '' +
                    '<ul>' +
                        '<li ng-repeat="person in list" ng-click="setSelected({person:person})">{{person.uri}}</li>' +
                    '</ul>' +
                '',
                link: function postLink(scope, element, attrs) {

                }
            };
        }
    ]);

工作的笨蛋:

https://plnkr.co/edit/KUWZ9bYbhnbumFwIgcIX?p=preview

于 2016-06-26T21:05:09.703 回答