Same data in multiple views using AngularJS

后端 未结 2 1132
太阳男子
太阳男子 2021-02-04 17:58

Maybe there is someone who can help me a little bit. I have to share data between multiple views. Because it is a school project, I have to use AngularJS, but I am new to it and

2条回答
  •  长发绾君心
    2021-02-04 18:39

    Since you are new to angularjs an easier approach would be to use $rootScope to share data between your controllers (and the views associated with them).

    Here is an example:

    angular.module('MyApp', [])
    
    .config(['$routeProvider', function ($routeProvider) {
      $routeProvider
        .when('/', {
          templateUrl: '/views/main.html',
          controller: 'MainCtrl'
        })
        .when('/first-page', {
          templateUrl: '/views/first.html',
          controller: 'FirstCtrl'
        })
        .when('/second-page', {
          templateUrl: '/views/second.html',
          controller: 'SecondCtrl'
        });
    }])
    
    .controller('MainCtrl', ['$rootScope', function ($rootScope) {
      // Will be available everywhere in your app
      $rootScope.users = [
        { name: 'Foo' },
        { name: 'Bar' }
      ];
    }])
    
    .controller('FirstCtrl', ['$rootScope', '$scope' function ($rootScope, $scope) {
      // Only available inside first.html
      $scope.bazUser = { name: 'Baz' };
      // Add to global
      $rootScope.users.push($scope.bazUser);
    }])
    
    .controller('SecondCtrl', ['$rootScope', '$scope' function ($rootScope, $scope) {
      console.log($rootScope.users); // [{ name: 'Foo' }, { name: 'Bar' }, { name: 'Baz' }];
    }]);
    

    inside second.html for example

    • {{user.name}}

提交回复
热议问题