是否可以将范围继承到子页面



>我有一个看起来像这样的网址结构:

    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 上的倒数第二个示例。他们使用了模块。

它应该有帮助。

让我知道它是否有帮助..

根据您的需求,您可以将通用功能放入原型中并将其用于控制器。有关原型的使用,请参阅 ngController 文档(不过,该示例不使用继承)。

另一种解决方案是侦听父范围中的位置事件,并在其中设置属性。有关事件,请参阅$location文档。

您可以使用

$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"));

}

最新更新