one controller two view

2019-05-21 11:03发布

问题:

I have a view where the user gives an input and display it in another view.

view 1:

<ion-content ng-controller="controller">
<input type="text" ng-model="name">
<button ng-click="save()">Save</button>

Controller:

   $scope.save = function () {
    $scope.displayName = $scope.name;
    $state.go('app.viewTwo');
}

View 2:

<ion-content ng-controller="controller">
{{displayName}}
</ion-content>

Its known, that whenever a view is loaded the controller is initialized fresh every time. So how to display the value from the first view, in another view.

回答1:

You need to use a service or factory to use the variable across the controllers.

DEMO:

 var app = angular.module("clientApp", [])
 app.controller("TestCtrl", 
   function($scope,names) {
     $scope.names =[];
    $scope.save= function(){
      names.add($scope.name);
    }
   
   $scope.getnames = function(){
     $scope.names = names.get();
   }
   }
  );
   
app.factory('names', function(){
  var names = {};

  names.list = [];

  names.add = function(message){
    names.list.push({message});
  };
  
  names.get = function(){
    return names.list;
  };

  return names;
});
<!doctype html>
<html >

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="clientApp">
  <div ng-controller="TestCtrl">
    <input type="text" ng-model="name">
    <button ng-click="save()" > save</button>
    
  </div>
  
  <div ng-init="getnames()" ng-controller="TestCtrl">
     <div  ng-repeat="name in names">
       {{name}}
       </div>
     
  </div>
</body>

</html>

You can also use $rootScope , but it is not a recommended way.