角服务:视图变化时损失的价值损失



我正在尝试构建一个简单的角度应用,该应用程序从Instagram中汲取数据。用户在索引页面上输入一个主题标签,然后将显示带有该主题标签的帖子的另一个页面显示。

我尝试传递用作服务中变量的主题标签,但是当视图更改时,值将被覆盖。(我可以在设置并设置它后立即检查该值,但是一旦页面更改,我就会丢失值)。

这是我的服务:

var instagramApp = angular.module('instagramApp')
.factory('feedData', function($rootScope) {
    var config = {};
    return {
        setHashtag: function (x) {
                config.hashtag = x;
        },
        getHashtag: function () {
            return config.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'
    });
}
]);

@pcguru提到的,当您运行此行$window.location.href = '/results.html';时,您的Angular应用会被浏览器重新加载。

当用户单击页面上的链接或设置$location.path('/someurl');时,Angular检测到URL的变化(这是用于获取/设置URL信息的角度服务)。您的JavaScript绕过。

请注意$ location

上的Angular Docs

它[$ location]不做什么?

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

如果要编程更改URL,请使用$location.path(url),如果您希望用户单击链接并转到应用程序中的新位置,而无需浏览器重新加载页面,则需要使用angular-route.js(https:https:https: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'
         });
    }
}());

您需要使用Angular的路由器来处理位置更改。这样,当您进入详细信息视图时,您将不会从头开始重新加载整个应用程序。

参见Angular的路由文档。

@pcguru所说,您需要使用Angular Router或UI-Router来保留单个Angular页面的上下文。

AngularRouter是角框架的一部分,易于使用。ui-router是一种补充,它更加恰当,并且允许您同时使用多个视图。如果您启动Angular,则可能不需要添加额外的复杂性。

使用类似$window.location.href = '/results.html';的内容将执行页面重定向,因此会重新加载您的页面。这不是在Angular

中进行操作的方法

最新更新