angular 指令调用带参数的控制器方法

angular directive call to controller method with parameter

我有一个带有获取参数方法的控制器, 我想要一个指令来调用该方法并传递参数。

当用户单击指令内的标签时,如何向控制器添加标签。

一些代码:

app.controller('MainCtrl', function($scope) {

    $scope.chosenTags = ['clickToRemoveMe', 'if you click on tags below they should appear here'];

    $scope.jokes = [{
        id: 0,
        content: 'bla bla bla bla',
        tags: ['fat', 'blondes']
    },{
        id: 1,
        content: 'another another another ',
        tags: ['thin', 'dark']
    }];

    $scope.addTag = function(tag) {
        $scope.chosenTags.push(tag);
    },

    $scope.removeTag = function(tag) {
        removeA($scope.chosenTags, tag);
    }

});

app.directive("joke", [function () {

    return {
        restrict: 'E',
        templateUrl: 'joke.html',
        scope: {
            joke: '='
        }
    };
}]);

笨蛋:http://plnkr.co/edit/Vpip4mWmWeH8Lvi7I5t5?p=preview

您正在使用隔离作用域,因此 ng-click="addMe(tag)" 不会执行任何操作,因为 addMe 函数在作用域中的任何位置都不存在。

您有多种选择,但我只是添加了函数引用并将其放在范围内:

指令:

scope: {
    joke: '=',
    addMe: '='
}

HTML:

<joke ng-repeat="joke in jokes" joke="joke" add-me="addTag"></joke>

Plunker

此外,您还应该在插入 chosenTags 数组之前添加检查,以避免这些控制台错误:

$scope.addTag = function(tag) {
    if ($scope.chosenTags.indexOf(tag) === -1) {
        $scope.chosenTags.push(tag);
    }
}