2015-05-05 17 views
2

我正在尝试构建一个简单的角度应用程序,该应用程序可以从Instagram中获取数据。用户在索引页上输入hashtag,然后显示到另一个页面,其中显示带有该hashtag的帖子。角度服务:查看更改时丢失的值

我试过传递用作服务中变量的hashtag,但是当视图改变时,该值被覆盖。 (我可以在设置它之后检查它的值,并且它已设置,但只要页面更改,我将失去该值)。

这里是我的服务:

var instagramApp = angular.module('instagramApp') 
.factory('feedData', function($rootScope) { 
    var config = {}; 
    return { 
     setHashtag: function (x) { 
       config.hashtag = x; 
     }, 
     getHashtag: function() { 
      return config.hashtag; 
     } 
    } 
}); 

和我的两个控制器:

集包括hashtag(在/index.html视图):

instagramApp.controller('indexController', ['$scope', 'feedData', '$window', 
function($scope, feedData, $window){ 

$scope.generate = function(){ 
    feedData.setHashtag('marcheet'); 
    console.log(feedData.getHashtag()); 
    $window.location.href = '/results.html'; 
}; 

}]); 

获取包括hashtag(在/results.html查看):

instagramApp.controller('instagramController', ['$scope', 'Instagram', '$http', 'feedData', 
function($scope, Instagram, $http, feedData){ 

    feedUrl = '/feed/?hashtag=' + feedData.getHashtag() +'&count=20'; 
    console.log(feedUrl); 
    createStoryJS({ 
     type:  'timeline', 
     width:  '800', 
     height:  '600', 
     source:  feedUrl, 
     embed_id: 'my-timeline' 
    }); 
} 
]); 
+5

$ window.location.href = '/results.html' 的配置方法;这条线就在这里,你刚刚离开了你的角度应用程序,所以这就是为什么它不知道它。 –

回答

3

正如@pcguru所提到的那样,当您运行此行时,您的角度应用程序将被浏览器重新加载。

当用户点击页面上的链接或通过设置$location.path('/someurl');(这是getting/setting url information的角度服务)时,Angular会检测URL中的更改。你的javascript规避了这一点。

注意Angular docs on $location

是什么[$位置]不能做?

当浏览器URL更改时,它不会导致整个页面重新加载。 要在更改URL后重新加载页面,请使用低级API $ window.location.href。

如果你想以编程方式更改URL,使用$location.path(url),如果您希望用户点击一个链接,去到一个新的位置在应用程序而无需浏览器重新加载页面,那么你需要设置使用angular-route.js路由(https://code.angularjs.org/1.3.15/angular-route.js),然后注入$routeProvider到应用

(function() { 
    'use strict'; 

    var app = angular.module('instagramApp', ['ngRoute']); 

    app.config(configFunc); 

    function configFunc($routeProvider) { 
     $routeProvider.when('/', { 
      templateUrl: 'path/to/your/template.html', 
      controller: 'HomeController' 
     }) 
     .when('/results', { 
      templateUrl: 'path/to/your/template.html', 
      controller: 'ResultsController' 
     }); 
    } 
}()); 
0

在@pcguru的帮助下,您需要使用angular Routerui-router来保留单个Angular Page的上下文。

AngularRouter是Angular框架的一部分,使用简单。 Ui-Router是一个补充,它可以更好地协调并允许您同时使用多个视图。如果你开始使用角度,这可能不需要增加额外的复杂性。

使用类似这样的东西$window.location.href = '/results.html';将执行页面重定向,因此将重新加载你的页面。 这不是在角度上做的方式