AngularJS从指令中的控制器调用方法?

时间:2014-09-14 12:40:36

标签: javascript angularjs

我有一个问题:我使用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);

1 个答案:

答案 0 :(得分:0)

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

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)
  }
})