我试图将视图中的数据共享到Ionic中的控制器。
我实际上在第一个视图中有一个表单:
<form action="#/app/result" method="post">
<select name="first">
<option value="1">a</option>
<option value="2" selected>b</option>
</select>
<select name="second">
<option value="1">a</option>
<option value="2" selected>b</option>
</select>
<button type="submit" class="button button-block button-positive">Go!</button>
</form>
在我的控制器中,我试图获得第一个&#34;和&#34;第二&#34;发布变量:
.controller('doSearchCtrl', function($scope, $stateParams, $http) {
var first = $stateParams.first;
var second = $stateParams.second;
...
}
但$ stateParams.first和$ stateParams.second无论如何都是空的(我也尝试将方法更改为&#34; get&#34;)
将这些变量从视图传递到控制器的最佳(且最有效)方法是什么?我看到一些代码使用服务但只是一个变量,所以不能适用于这个例子...
由于
答案 0 :(得分:1)
最终,您确实希望使用服务在控制器/视图之间共享变量。请参阅下面的代码段以了解我的修改。
一些注意事项:
forms
/ submit
更改为使用ng-click
,但如果符合您的目的,则应使用submit
。ng-options
)。ng-model
。这为ng-model
变量/对象设置了双向绑定,该绑定将在该控制器的$scope
上提供。service
中。您可以使用getter / setter方法,如下面的代码段所示。当您点击代码段中的按钮时,controller 1
会将您的选择存储在服务中。您可以通过添加另一个视图/控制器来扩展它,您将能够从服务中检索这些值。示例代码显示在controller 2
。
希望这是有道理的。
angular.module('ionicApp', ['ionic'])
.controller('Ctrl1', function($scope, letterService, $stateParams, $http) {
$scope.firstList = ["a", "b"];
$scope.secondList = ["a", "b"];
$scope.set = function(first,second) {
letterService.setLetters(first,second);
alert("First letter = " + first + " and Second letter =" + second + ". These have been updated in letterService and can be called by any other controller in a different view");
//You should put your http requests in a service, but you can execute it here/do routing.
}
})
.controller('Ctrl2', function($scope, letterService) {
$scope.firstLetter = "a";
$scope.secondLetter = "b";
$scope.get = function() {
//get updated letters from letterService
var selectedLetters = letterService.getLetters();
$scope.firstLetter = selectedLetters.firstLetter;
$scope.secondLetter = selectedLetters.secondLetter;
}
})
.factory('letterService', function() {
var selectedLetters = {}
return {
setLetters: function(firstLetter,secondLetter) {
selectedLetters.firstLetter = firstLetter;
selectedLetters.secondLetter = secondLetter;
},
getLetters: function() {
return selectedLetters;
}
}
})
&#13;
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic Template</title>
<link href="http://code.ionicframework.com/1.0.0-beta.2/css/ionic.css" rel="stylesheet">
<script src="http://code.ionicframework.com/1.0.0-beta.2/js/ionic.bundle.js">
</script>
</head>
<body ng-controller="Ctrl1">
</ion-content>
<div>
<select ng-init="first = firstList[0]" ng-model="first" ng-options="letter for letter in firstList "></select>
<select ng-init="second = secondList[0]" ng-model="second" ng-options="letter for letter in secondList "></select>
<button class="button button-small button-positive" ng-click="set(first,second)">Store these options in a service</button>
</div>
</ion-content>
</body>
</html>
&#13;