指令中来自控制器的AngularJS调用方法

AngularJS call method from controller in directive?

本文关键字:AngularJS 调用 方法 控制器 指令      更新时间:2023-09-26

我有一个问题:我使用Angular,需要使用pushMsg方法,但我不知道如何调用它,boxCtrl.pushMsg(msg)不起作用。

app.directive("fileread", function (socket) {
return {
    scope: {
        fileread: "="
    },
    link: function (scope, element, attributes) {
        element.bind("change", function (changeEvent) {
        var msg = { author: 'me', class: 'me' };
           // WHAT HERE???????
        });
    }
}
});
boxCtrl = function (socket, $scope) {
    this.messages = [];
}
boxCtrl.prototype = {
    pushMsg: function (message) {
        this.messages.push(message);
    }
}
app.controller('boxCtrl', boxCtrl);

您创建一个独立的作用域并将其作为属性传递:

app.directive("fileread", function (socket) {
return {
    scope: {
        fileread: "=",
        pushMessage: "="
    },
    link: function (scope, element, attributes) {
        element.bind("change", function (changeEvent) {
        var msg = { author: 'me', class: 'me' };
        scope.pushMessage(msg);
        });
    }
}
});

在您的HTML:中

<div fileread="..." push-message="pushMsg">

编辑:你的控制器应该是这样的:

app.controller('Ctrl', function($scope) {
  $scope.messages = [];
  $scope.name = function(msg) {
    $scope.messages.push(msg);
    $scope.$apply(); //I think you need this to update the UI (not sure though)
  }
})