在AngularJS控制器之间共享数据我正在尝试跨控制器共享数据。用例是一种多步形式,在一个输入中输入的数据稍后用于原始控制器外的多个显示位置。下面的代码和jsfiddle这里。HTML<div ng-controller="FirstCtrl">
<input type="text" ng-model="FirstName"><!-- Input entered here -->
<br>Input is : <strong>{{FirstName}}</strong><!-- Successfully updates here --></div><hr><div ng-controller="SecondCtrl">
Input should also be here: {{FirstName}}<!-- How do I automatically updated it here? --></div>JS// declare the app with no dependenciesvar myApp = angular.module('myApp', []);
// make a factory to share data between controllersmyApp.factory('Data', function(){
// I know this doesn't work, but what will?
var FirstName = '';
return FirstName;});// Step 1 ControllermyApp.controller('FirstCtrl', function( $scope, Data ){});
// Step 2 ControllermyApp.controller('SecondCtrl', function( $scope, Data ){
$scope.FirstName = Data.FirstName;});任何帮助是极大的赞赏。
4 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
我不喜欢$watch
这样做。您可以只分配数据,而不是将整个服务分配给控制器的范围。
JS:
var myApp = angular.module('myApp', []);myApp.factory('MyService', function(){ return { data: { firstName: '', lastName: '' } // Other methods or objects can go here };});myApp.controller('FirstCtrl', function($scope, MyService){ $scope.data = MyService.data;});myApp.controller('SecondCtrl', function($scope, MyService){ $scope.data = MyService.data;});
HTML:
<div ng-controller="FirstCtrl"> <input type="text" ng-model="data.firstName"> <br>Input is : <strong>{{data.firstName}}</strong></div><hr><div ng-controller="SecondCtrl"> Input should also be here: {{data.firstName}}</div>
或者,您可以使用直接方法更新服务数据。
JS:
// A new factory with an update methodmyApp.factory('MyService', function(){ return { data: { firstName: '', lastName: '' }, update: function(first, last) { // Improve this method as needed this.data.firstName = first; this.data.lastName = last; } };});// Your controller can use the service's update methodmyApp.controller('SecondCtrl', function($scope, MyService){ $scope.data = MyService.data; $scope.updateData = function(first, last) { MyService.update(first, last); }});
添加回答
举报
0/150
提交
取消