2016-09-03 208 views
0

我有page1.html有一个对象列表,当用户点击一个对象时,网站应该导航到其他页面并显示对象的详细信息。html页面之间共享数据 - angularJs

1.HTML页AHS表中,每行是对象:

<tr ng-repeat="abjcet in nc.object"> 
      <td>{{object.title}}</td> 
    </tr> 

2,当用户点击标题相同的对象必须转移到下一个HTML页面,我已经尝试这一点,我的对象被检索,但我不知道如何保存它,并在接下来的HTML页面中使用它:

<tr ng-repeat="object in nc.objects"> 
    <td ng-click="getById(object.id)">{{object.title}}</td> 
</tr> 

我的控制器:

(function() { 
    'user strict'; 

    angular.module('app').controller('myController', myController); 

    myController.$inject = ['$http', '$scope' ]; 

function myController($http , $scope) { 

     var nc = this; 
     nc.objects = []; 
     nc.object = null; 

    nc.getById = getById ; 

    init(); 


    function init(){ 
     getAll(); 

    } 

    function getAll() 
    { 
     var url = "/getAll/"; 
     var Request = $http.get(url); 
     Request.then(function (response) { 

      nc.objects = response.data; 

     }); 
    } 

    function getById(id) { 

     var url = "/findById/"+id; 
     var Request = $http.get(url); 
     Request.then(function (response) { 

      nc.object = response.data; 

     }); 
    } 

} 
})(); 

回答

2

如果您需要导航到另一个页面,或者使用SPA(单页应用程序)和跨所有控制器共享数据的服务,则可以使用localStorage。

// Save the title 
localStorage.setItem('title', $scope.title); 
// Retrieve the title 
$scope.title = localStorage.getItem('title'); 
0

如果您的HTML应用程序为completely a single page application,则将$rootScope添加到myController.$inject,然后将其保存在$rootScope中,可以在多个页面中访问它。

相反,如果您有两个控制器在不同页面上使用的service,请在该变量的service中执行getters and setters

希望它可以帮助你!

+0

这不是角的方式,他们居然劝你从来没有使用'$ rootScope'保持任何形式的状态。事件是'$ rootScope'应该使用的唯一的东西。 –

0

多解

  1. 使用本地存储,可以维护一个数据,并在多个页面坚持它,这是最安全和最简单的方法。开箱即用的模块有很多,并且做得很好:Angular local storage

实施例:

myApp.controller('MainCtrl', function($scope, localStorageService) { 
    // setter 
    localStorageService.set('title', 'value'); 
    // getter 
    var title = localStorageService.get('title'); 
}); 
  • Routing 可以使用路由通过SPA(单页应用程序)保持的数据,这将停止浏览器从实际重新加载网页,并允许用户请求下一个视图/页面。这意味着您可以将数据保存在工厂中,数据将保存在内部存储器中。
  • 例子:

    //factory 
    myApp.factory('Data', function() { 
        var data = {}; 
        return { 
         get :get, 
         set : set 
        }; 
        // setter 
        function set(key, val){ 
         data[key] = val; 
        } 
        // getter 
        function get(key) { 
         return data[key] || null; 
        } 
    }); 
    
    myApp.controller('MainCtrl', function(Data) { 
        // setter 
        Data.set('title', 'value'); 
        // getter 
        var title = Data.get('title'); 
    });