2014-04-04 39 views
0

我有一個URL結構,看起來像這樣:您可以將範圍繼承到子頁面嗎?

when('/:location',{ 
     controller: 'locationController', 
     templateUrl: 'partials/single.html', 
    }). 
    when('/:location/karta',{ 
     redirectTo: '/:location/karta/CYKLING' 
    }). 
    when('/:location/karta/:type',{ 
     templateUrl: 'partials/directions.html' 
    }). 

及以下控制器:爲相同

controller('locationController', function($scope, $location, $routeParams, instagram, swimlocations) { 
     $scope.name = $routeParams.location; 
     $scope.location = swimlocations.getLocation($routeParams.location) 
     instagram.getPhotosByLocation($scope.location.long,$scope.location.lat, 100, function(data){ 
      $scope.images = data; 
     }); 
}). 
controller('directionController'. function($scope, $location, $routeParams, swimlocations) { 
    $scope.name = $routeParams.location; 
     $scope.location = swimlocations.getLocation($routeParams.location) 
}). 

正如你可以看到,兩個控制器都好,除了第一一個向instagram發出請求。有什麼辦法可以避免這種代碼重複?

回答

0

Angular具有「模塊」概念... 您需要具有模塊種類的結構,這將使所有資源可用於子控制器。

例如在Angularjs.org上查看第二個最後一個示例。他們使用了模塊。

它應該幫助。

讓我知道如果它可以幫助..

+0

有什麼例子的名字嗎? – Himmators

+0

其實我的網速度慢...不能夠jsfiddle ....名稱=連線後端....在網站前面 – vijay

+0

不,我不明白.... – Himmators

0

根據您的需求,您可以把常用的功能集成到一個原型,並使用您的控制器。請參閱ngController docs以瞭解原型的使用(但該示例不使用繼承)。

另一種解決方案是偵聽父範圍中的位置事件並在其中設置屬性。有關事件,請參閱$location docs

0

你可以用$ rootScope功能做(也許不是最完美的方式,但它很容易):

你的模塊/配置,你向我們展示了路由後添加此。

when('/:location',{ 
     controller: 'locationController', 
     templateUrl: 'partials/single.html', 
    }). 
    when('/:location/karta',{ 
     redirectTo: '/:location/karta/CYKLING' 
    }). 
    when('/:location/karta/:type',{ 
     templateUrl: 'partials/directions.html' // doesnt this need a controller to be caled? 
    }) 
    .run(function($rootScope) { 

     $rootScope.var = null; //global variable 


    $rootScope.globalFoo = function(variable) { 
     alert("I'm global function with variable! " + variable); 
    }; // you can make your function here and make an IF to check what kind of calls u need to make 

$rootScope.globalFooReturn = function(variable) { 
     return "I'm global function with variable! " + variable; 
    }; 

然後$ rootScope添加到您的控制器並調用函數來觸發它:

controller('locationController', function($rootScope, $scope, $location, 
$routeParams, instagram, swimlocations){ 

$rootScope.globalFoo("Instagram"); 

$scope.message = $rootScope.globalFooReturn("Instagram"); 
alert($scope.message); 

//or 
alert($rootScope.globalFooReturn("Instagram")); 


}