Angularjs 是否可以使作用域继承到子页?
我的url结构如下所示:Angularjs 是否可以使作用域继承到子页?,angularjs,Angularjs,我的url结构如下所示: when('/:location',{ controller: 'locationController', templateUrl: 'partials/single.html', }). when('/:location/karta',{ redirectTo: '/:location/karta/CYKLING' }). when('/:location/karta/:type'
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发出请求外,这两个控制器完全相同。有没有办法避免这种代码重复?Angular有“模块”的概念。。。
您需要有一种模块类型的结构,使所有资源都可用于子控制器
例如,参见Angularjs.org上的最后第二个示例。。他们使用了这个模块
这应该会有帮助
如果有帮助,请告诉我。根据您的需要,您可以将通用功能放入原型中,并将其用于控制器。有关原型的使用,请参见(不过,该示例不使用继承)
另一个解决方案是侦听父作用域中的位置事件并在那里设置属性。有关事件的详细信息,请参阅 您可以使用$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"));
}
这个例子的名字是什么?实际上我的网络速度很慢…无法在网站前面连接后端