Angular JS深层链接将刷新视图

时间:2014-05-19 03:01:11

标签: javascript angularjs angularjs-scope angularjs-routing

我会尽力解释这个问题。我也是Angular的新手,所以请耐心等待。

我有两条使用相同模板的路线......

ExampleApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/logbook/following', {
        templateUrl: 'views/surf.html',
    })

    .when('/logbook/following/:surf_id', {
        templateUrl: 'views/surf.html',
    })
}]);

有两个控制器

AppControllers.controller('LogbookController', function($scope, $http, $location, $routeParams) {

    $scope.surfs = null;

    // Get feed
    $http.get(RestURL + 'feeds?filter=following' ).success(function(data) {

        if(typeof $routeParams.surf_id == "undefined") {

            if(data.length > 0) {

                $location.path('/logbook/following/' + data[0].id);
                $scope.loadSurfDetail(data[0].id);
            }
        }

        $scope.surfs = data;
    });
});


AppControllers.controller('SurfController', function($scope, $http, $location, $routeParams) {

    $scope.loading = false;

    // Load surf
    $scope.loadSurfDetail = function(surfID) {
        $scope.loading = true;
        $scope.selectedSurf = null;

        // Get surf
        $http.get(RestURL + 'surfs/' + surfID).success(function(data) {
            $scope.selectedSurf = data;
            $scope.loading = false;
        });
    };

    if($routeParams.surf_id) {
        $scope.loadSurfDetail($routeParams.surf_id);
    }
});

使用此模板文件:

<div class="row">
    <div class="logbook col-md-3" ng-controller="LogbookController">
        <h1>Logbook</h1>
        <ol class="surfs-feed">
            <li data-id="{{feedSurf.id}}" ng-repeat="feedSurf in surfs" class="surf">
                <a href="#/logbook/following/{{feedSurf.id}}">
                    <strong>{{feedSurf.user.first_name}} {{feedSurf.user.last_name}}</strong>
                </a>
            </li>
        </ol>
    </div>
    <div class="surf col-md-9" ng-controller="SurfController">
        <p class="alert alert-info" ng-show="loading">
            Loading...
        </p>
        <div class="surf-detail" ng-show="selectedSurf">
            <pre>
                {{selectedSurf | json}}
            </pre>
        </div>
    </div>
</div>

我的问题是,当我加载深层链接网址时,即。 / logbook / following /:surf_id它将使用与/ logbook / following(adove)相同的模板,这将导致每次加载新冲浪时重新生成日志源。因此,每次加载冲浪时,日志都会闪烁&#34;并重新生成。

我想知道人们如何解决这个问题,而无需刷新冲浪信息,只需更新右侧的详细信息面板......

谢谢!

1 个答案:

答案 0 :(得分:0)

在你的app配置中,注入$ locationProvider并将其html5Mode参数设置为true。然后,路由更改不会导致页面刷新。

ExampleApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider

    .when('/logbook/following', {
        templateUrl: 'views/surf.html',
    })

    .when('/logbook/following/:surf_id', {
        templateUrl: 'views/surf.html',
    })

    $locationProvider.html5Mode(true);
}]);