AngularJS指令 - 初始调用函数

时间:2016-12-28 21:33:25

标签: angularjs angularjs-directive

我使用这个指令:

function communicationCreateFormDirective($timeout) {
    var directive = {
        restrict: 'E',
        scope: {
            selectedCommunicationGroups: '=',
            currentUser: '='
        },
        templateUrl: 'app/communication/....html',
        link: function($scope) {
            ...
            connect();

我将最初调用函数connect(),但我收到错误:

angular.js:14110 ReferenceError: connect is not defined

$ scope.connect()也不起作用。有谁知道该怎么做?

这个功能:

$scope.connect = function() {
                var socket = new SockJS('/api/chat');
                $scope.stompClient = Stomp.over(socket);            
                $scope.stompClient.connect({}, function(frame) {
                    console.log('webSocket Connected in communicationCreateForm.directive.js: ' + frame);
                    $scope.stompClient.subscribe('/topic/communication/' + $scope.currentUser.id, function(message) {
                        //vm.showMessage(JSON.parse(message.body));
                        alert('Message response QUMA: ' + JSON.parse(message.body));
                    });
                });
            }

1 个答案:

答案 0 :(得分:1)

您的指令正在创建一个新的隔离范围,该范围无法直接访问您定义连接的控制器的范围。您需要传递类似于传递selectedCommunicationGroupscurrentUser的函数的函数,以使其位于链接函数的范围内。

function communicationCreateFormDirective($timeout) {
  var directive = {
    restrict: 'E',
    scope: {
      selectedCommunicationGroups: '=',
      currentUser: '=',
      connect: '=' // <- "links" the scopes together
    },
    templateUrl: 'app/communication/....html',
    link: function($scope) {
      ...
      $scope.connect();

HTML:<wheverYouCalledIt connect="connect" ... >

您也可以使用'&'代替'='进行连接,这样可以让您在调用函数时传递更多内容,但看起来并不需要。如果您这样做,HTML属性会稍微改为connect="connect()"