本文介绍了一个控制器两个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个视图,用户提供输入并在另一个视图中显示。
I have a view where the user gives an input and display it in another view.
查看1:
<ion-content ng-controller="controller">
<input type="text" ng-model="name">
<button ng-click="save()">Save</button>
控制器:
$scope.save = function () {
$scope.displayName = $scope.name;
$state.go('app.viewTwo');
}
查看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.
推荐答案
你需要使用或在控制器上使用变量。
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>
你也可以使用$ rootScope,但这不是推荐的方式。
You can also use $rootScope , but it is not a recommended way.
这篇关于一个控制器两个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!