2013-08-02 13 views
5

ここに私の状況を例示するjsfiddleがあります。AngularJSの隔離されたスコープ/ディレクティブからのブロードキャストとコールコントローラ機能の受信?

まず、受け取ったディメンションでディレクティブを作成する正しい方法はありますか? その後、それぞれの指示は他の指示と隔離されるべきです。したがって、私はscope: {}を使用しています。

..問題は...コントローラである関数を呼び出しているし、いずれかの放送を受信して​​いないようだ私は、これは些細な問題であると確信しています..私は角に新しいです:)

<div ng-app="test"> 
    <div ng-controller="containerCtrl"> 
     <component ng-repeat='c in components' id="c.id" my-width="{{c.width}}" my-height="{{c.height}}"> 
    </div> 
</div> 

コントローラ:

controller('containerCtrl', function ($scope) { 
    $scope.components = [{ id: "c1", width: 100, height: 100 }, 
         { id: "c2", width: 200, height: 100 }, 
         { id: "c3", width: 300, height: 100 }]; 

    //in the actual controller I am using a socket provider and doing 
    //socket.forward([ 
    //  'initPage', 
    //  'refreshPage' 
    // ], $scope); 
    //simulating it with a simple broadcast here.. 
    $scope.$broadcast("onSomething", ""); 

    $scope.doSomething = function (data) { 
     alert("doing something"); 
    }; 
}). 

は私がNGリピートを有する部品の数をロードするページを有します

とディレクティブ:

directive('component', function() { 
     var linkFn = function(scope, element, attrs) { 
      $(element). 
       resizable({ 
        stop: function(event, ui) { 
         scope.emitSomething(attrs.id, ui.position); 
        } 
       }); 

      scope.$on('onSomething', function(res) { 
       alert("onSomething!"); 
      }); 
     }; 

     return { 
      restrict: 'E', 
      template: '<div class="ui-widget-content" style="width: {{width}}px; height: {{height}}px;"></div>', 
      replace: true, 
      scope: { 
       width:'@myWidth', 
       height:'@myHeight' 
      }, 
      link : linkFn 
     }; 
    }); 

答えて

16

コントローラは、リンク関数の前に実行されるので、あなたの放送があまりにもすぐに送信されています。あなたは$timeoutを使用して、これを遅らせることができます。

$timeout(function() { 
    $scope.$broadcast("onSomething", ""); 
}); 

は、分離株のスコープとディレクティブからコントローラメソッドを呼び出すには、引数としてメソッドを指定する必要があります。

<component ng-repeat='c in components' id="c.id" my-width="{{c.width}}" 
my-height="{{c.height}}" callbk="doSomething(data)"> 

を、あなたが使用する必要がありますディレクティブで&構文::

scope: { 
    width: '@myWidth', 
    height: '@myHeight', 
    emitSomething: '&callbk' 
}, 

そのコールバック/コントローラ機能にパラメータを渡すには、適切な構文を使用する必要があります。フィドルでは、私は引数を1つしか使用され、代わりに、アレイ内の2つのパラメータを渡す:

$(element).resizable({ 
    stop: function (event, ui) { 
     scope.emitSomething({data: ["id", "position"]}); 
    } 
}); 

fiddle

+0

パーフェクト、感謝を:)ここで働いてjsfiddle http://jsfiddle.net/dr9c6/6/タグで宣言された関数がコントローラ内部の関数であり、 '{data:}'を受け取る関数が指令スコープの関数であると言うのは正しいですか? – fusio

+1

@fusio、そうだね。 –

+0

私は同様の問題を抱えています...コントローラーからのブロードキャストはディレクティブでイベントを発生させません...タイムアウトは時々これを解決しますが、必ずしもそうではありません...また、アプリケーションはかなり重く、事実、時間は常にそれを解決するだろう...それを行うための他の方法はありますか? – ackuser

関連する問題