角度-点击时从控制器运行函数

Angular - running functions from controller on ng-click

本文关键字:控制器 运行 函数 -点 角度      更新时间:2023-09-26

我想在加载指令时运行一些函数,然后能够使用ng-click再次"重新运行"它。我的代码如下:

const app = angular.module('app', []);
class dummyController {
    logIt() {
        console.log('logging');
    }
}
app.directive('dummyDir', () => {
    return {
        controller: dummyController,
        link(scope, element, attrs, ctrl) {
            scope.logIt = ctrl.logIt();
            scope.logIt;
        }
    };
});

HTML

<div ng-app="app">
    <button class="reinit" type="submit" dummy-dir ng-click="logIt()">Reinit</button>
</div>

CodePen

不幸的是,点击按钮没有任何作用。我做错了什么?

在行中

scope.logIt = ctrl.logIt();

您实际上是在调用logIt函数,并将该函数的结果分配给变量logIt。该函数不返回任何内容,因此结果是未定义的。

相反,您需要为变量分配一个指向函数的指针,以便稍后使用:

link(scope, element, attrs, ctrl) {
    scope.logIt = ctrl.logIt;    // assign a function, do not invoke it
    scope.logIt();               // invoke the function
}
class dummyController {
    logIt() {
        console.log('logging');
    }
    logIt();
}