2012-06-24 36 views
3

我想在AngularJS中使用$locationProvider服務,而無需在我的ng-view中呈現新的HTML模板。

我有一個div元素,通過ng-show按需顯示綁定到一個數據元素的存在。我想通過$locationProvider將其連接到瀏覽器位置,但保持在同一模板中。

模板:

<div> other stuff ... </div> 

<div ng-show="model">{{ model.element }}</div> 

控制器:

Controller = function($scope, $location) { 
    $scope.show = function() { 
    $scope.model = model; // show div 
    } 

    $scope.hide = function() { 
    $scope.model = null; // hide div 
    } 
} 

我無法弄清楚如何將$location服務在這個整合。如果直接設置了history.pushState,AngularJS也會覆蓋該位置。

回答

6

使用源,盧克:-) http://code.angularjs.org/1.0.0/angular-1.0.0.js

如果你看一下ngViewDirective(實際上是超級簡單),它只是抓住了「$ routeChangeSuccess」事件,並相應地改變看法。

因此,您可以捕獲$ routeChangeSuccess,然後將$ route注入您的控制器,檢查新路線是否是您想要的路線,然後相應地顯示。 (我認爲:d)

這可能工作(未經測試):

//declare a route so angular knows to broadcast about it when it's hit 
//We aren't declaring any actions for the route though, 
//since below we define custom actions 
myApp.config(function($routeProvider) { 
    $routeProvider.when('/superman', {}); 
}); 

function SupermanCtrl($scope, $route) { 
    $scope.$on('$routeChangeSuccess', function() { 
    //If this doesn't work, console.log $route.current to see how it's formatted 
    if ($route.current == '/superman') 
     $scope.show = true; 
    else 
     $scope.show = false; 
    }); 
} 

我希望它的作品,如果它不應該是足夠的開始。我鼓勵你閱讀ngViewDirective,如果這不起作用,搜索'$ routeChangeSuccess',並找出它爲什麼被廣播。

+0

謝謝,這是行不通的。我在這個解決方案中使用它:http://stackoverflow.com/a/15169779/215945 –