为什么指令不调用我的控制器方法

Why directive is not calling my controller method?

本文关键字:控制器 方法 我的 调用 指令 为什么      更新时间:2023-09-26

指令没有调用我的控制器方法。下面是我的代码:

控制器:

    exports.controller = ['$scope', function($scope) {
        $scope.addParamter = function () {
            console.log("here");
        };
       $scope.editParamter = function (item) {
            console.log(item);
       };
   }];

页面:

<formula-editor
    add-paramter="addParameter()"
    edit-paramter="editParameter(item)">
</formula-editor>

指令:

Js:

exports.inject = function(app) {
    app.directive('formulaEditor', exports.directive);
    return exports.directive;
};
exports.directive = function () {
    return {
        restrict: 'E',
        templateUrl: '/dist/views/formula-editor.html',
        scope: {
            addParameter: '&',
            editParameter: '&'
        }
    };
};

formula-editor.html:

<button ng-click="addParameter()"></button>

欢迎来到Angular !你在这里做了一个boo boo,你的$scope.addParamter()函数名称在你的HTML中是错误的(拼写错误),所以你的指令无法在指令标签中找到提到的addParameter()函数。所以只要把你的主html改成下面的

<formula-editor
    add-paramter="addParameter()"
    edit-paramter="editParameter(item)">
</formula-editor>

<formula-editor
    add-paramter="addParamter()"
    edit-paramter="editParamter(item)">
</formula-editor>

您可以尝试下面的代码。它可能对u有效。

exports.directive = function () {
    return {
        restrict: 'E',
        templateUrl: '/dist/views/formula-editor.html',
        scope: {
            addParameter: '&addParamter',
            editParameter: '&editParamter'
        }
    };
};

代替

<formula-editor
    add-paramter="addParameter()"
    edit-paramter="editParameter(item)">
</formula-editor>

可以用

<formula-editor
    addParamter="addParameter()"
    editParamter="editParameter(item)">
</formula-editor>