0

メイン コントローラーの 1 つの目標は、ユーザーが他のユーザーの URL にアクセスできないようにすることです。これは、$locationChangeStart をリッスンし、そのイベント preventDefault メソッドを使用することで完全に正常に機能します。残念ながら、このメソッドを呼び出すと、関数「handleNotification」の作業が何らかの形で「中断」されるという奇妙な副作用があります。この関数は、ユーザーが不正なことをしたことを 2 秒間通知することを目的としています。event.preventDefault() をコメントアウトすると、すべてが期待どおりに機能します。したがって、私の質問は次のとおりです。「デフォルト」の preventDefault の「スコープ」とは何ですか?

$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
    ifUserIs('loggedIn', function() {
        if (newUrl.split('#/users/')[1] !== $scope.user.userId) {
            handleNotification('alert', 'You are not allowed to go here.');
            event.preventDefault();
        }
    });
});

function handleNotification (type, message) {

$scope.notice = {
    content: message,
    type: type
};

$timeout(function() {
    delete $scope.notice;
    return true;
    }, 2000);
}
4

1 に答える 1

0

以下の更新

Ok。問題は別の場所にあります。関連するjsfiddleでは、すべて正常に動作します。この奇妙な動作の原因となっているソースを見つけた後、お知らせします。

<html ng-app="mapApp">
    <div ng-controller="mainCtrl">
        <global-error message="{{notice.content}}"></global-error>
    </div>

</html>

そしてコード。

var mapApp = {};
mapApp = angular.module('mapApp', []);
mapApp.controller('mainCtrl', function ($scope, $location, $timeout) {
    $location.path('users/2')

$scope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {

    handleNotification('alert', 'You are not allowed to go here.');
    event.preventDefault();

});

function handleNotification(type, message) {
    $scope.notice = {
        content: message,
        type: type
    };

    $timeout(function () {
        delete $scope.notice;
        console.log('deleted');
        return true;
    }, 2000);

   $scope.$digest();

}

});

mapApp.directive('globalError', function () {
    return {
        restrict: 'E',
        scope: {
            message: '@',
            type: '@'
        },
        template: "<div class=\"alert-box {{type}}\">\
                <p>\
                    {{message}}\
                </p>\
            </div>"
    };
});

アップデート OK。さらに一歩。そして、問題はまだ残っています。現在、ブラウザーでパスを変更することは$location.path('users/2')、コード内に配置して URL を変更することとは異なることを知っています (上記を参照)。期待どおりに$location.path('users/2')動作しますが、ブラウザーのアドレス バーのパスを手動で変更すると、通知が表示されずにアドレスが元のアドレスに戻るだけです。event.preventDefault()正しく動作しますが、 そうhandleNotification('alert', 'You are not allowed to go here.')ではありません。変。

Update 2$scope.$digest()関数の最後に 追加するとhandleNotificationうまくいきました。

于 2013-11-09T21:47:44.347 に答える