2016-03-25 35 views
0

我正在使用ui路由器與angularjs。我想爲視圖編寫一個模板,根據視圖的內容顯示圖像。這是我的示例狀態。有我的角度控制器檢查,以查看它與ui路由器位於什麼UI-

$stateProvider 
    .state('index', { 
     url: "", 
     views: { 

      "topStormtrooper": { 
       templateUrl: '/components/stormtroopers/stormtroopers.html', 
       controller: "stormtroopersCtrl" 
      }, 

      "bottomStormtrooper": { 
       templateUrl: '/components/stormtroopers/stormtroopers.html', 
       controller: "stormtroopersCtrl" 
      } 
     } 
    }) 

我的控制器看起來像這樣

.controller('stormtroopersCtrl', ['$scope', '$http', '$stateParams', function ($scope, $http, $stateParams) { 
// 
$scope.stormtrooper = $stateView; //it should be something like this hopefully 


}]); 

模板都是一樣的只是圖像將根據其查看被加載到不同的。目前我只是爲每個視圖添加了一個新的控制器,並基於該控制器加載圖像。但我覺得我應該可以用一個控制器來做到這一點,並且控制器應該能夠檢測到視圖是什麼。我知道你可以檢測到這個狀態,但是我想要更深入地瞭解這個視圖。

任何想法?

+0

您是否想要訪問控制器目前的狀態?像 'console.log($ scope.stormtrooper)//「index」' –

回答

0

您可以訪問當前狀態configuratin對象是這樣的:

$state.current

欲瞭解更多信息,看看在$state

0

你可以聽$viewContentLoaded功能在你的控制器按照ui-router documentation

例如:

.controller('stormtroopersCtrl', ['$scope', '$http', '$stateParams', function ($scope, $http, $stateParams) { 

$scope.$on("$viewContentLoaded",function(event,viewName){ //listen for when the content is loaded into the view 
    $scope.currentView = viewName; //assign the view name in a model 
    console.log($scope.currentView); 
    //do something because you got the view name now.... 

}); 

}]); 
+0

這似乎是正確的想法,除了參數viewName返回未定義。奇怪的是,它適用於我,如果我使用$ viewContentLoading,除非它爲每個正在加載的視圖啓​​動一個事件,這使得不可能知道這個stormtrooperCtrl加載的視圖。 – H0miet

+0

@ H0miet您正在使用哪個版本的角? – AhsanAyaz

+0

我正在使用版本1.4.4 – H0miet

0

您不需要爲模板中的圖像更改狀態。你可以使用範圍變量。

angular.module('app',[]) 
 
.controller('stormtrooperCtrl', ['$scope', function ($scope) { 
 
// 
 
    $scope.selected = 0; 
 
    $scope.images = [ 
 
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSz6dBOOsFVAeSilVEIO9dqwrY4R5gCzEMcrRVZguhYhr9PVJsThQ", 
 
    "http://www.wallpapereast.com/static/images/Wallpaper-Nature-8B71.jpg", 
 
    "http://www.intrawallpaper.com/static/images/1250654-for-laptop-nature.jpg" 
 
    ]; 
 

 

 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> 
 
<div ng-app="app"> 
 
    <div ng-controller="stormtrooperCtrl"> 
 
    <button ng-click="selected=0">image1</button> 
 
    <button ng-click="selected=1">image2</button> 
 
    <button ng-click="selected=2">image3</button> 
 
    <div> 
 
     <img width="100" ng-src="{{images[selected]}}"/> 
 
    </div> 
 
    </div> 
 
</div>