0

AngularJS で構築された単純なアプリがあります。

var App = angular.module('myApp', [], function($window) {
  // settings..
}).run(function($rootScope){
   $(window).on('resize', function(event) {
        $rootScope.$broadcast('windowResize',{
            height: event.target.innerHeight,
            width: event.target.innerWidth
        });
    });
});

panel次のコントローラーを使用したディレクティブがあります。

function($scope, $element) {    
    var
        $title = $element.find('.panel-title'),
        $content = $element.find('.panel-content'),
        margin = 20
    ;
    $content
        .height($(window).height() - $title.height() - margin);

    $scope.$on('windowResize', function(obj) {
        var height = obj.height - $title.height()  - margin;
        $content.height(height);
    });
}

すべてが初めて完全に機能します。ただし、コントローラーが変更されると、のような問題がTypeError: Cannot read property '$$childHead' of null発生しますが、エラーが発生する可能性があります。

問題は$scope.$on. $scope を破棄する前に (コントローラーが変更されたとき)、これを削除するにはどうすればよいですか?

4

2 に答える 2

2

この$on関数は、登録解除関数を返します。したがって、その関数を変数に格納し、イベントの登録を解除する必要があるときに関数を呼び出すことができます。

var deregisterWindowResize = $scope.$on('windowResize', function callback(args){...});

$scope.$on('$destory', deregisterWindowResize);

詳細はこちら


これを頻繁に使用する必要がある場合は、関数/サービスを作成できます。次のようなものが機能します。

function weakBind(scope, eventName, callback){
    var deregister = scope.$on(eventName, callback);
    scope.$on('$destroy', deregister);
    return deregister;
}

weakBind($scope, 'windowResize', function(obj) {
    var height = obj.height - $title.height()  - margin;
    $content.height(height);
});
于 2014-06-01T15:05:26.507 に答える
1

$destroy イベントをフックしてから、.$off を使用できます。

例えば:

var onWindowResize = function(obj) {
    var height = obj.height - $title.height()  - margin;
    $content.height(height);
});

$scope.$on('windowResize', onWindowResize);
$scope.$on('$destroy', function(){
    $scope.off('windowResize', onWindowResize);
});
于 2013-07-18T21:11:16.007 に答える