我试图在控制器之间共享数据。用例是多步骤形式,在一个输入中输入的数据稍后在原始控制器之外的多个显示位置中使用。代码在下面和在
jsfiddle here。
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 dependencies var myApp = angular.module('myApp',[]); // make a factory to share data between controllers myApp.factory('Data',function(){ // I know this doesn't work,but what will? var FirstName = ''; return FirstName; }); // Step 1 Controller myApp.controller('FirstCtrl',function( $scope,Data ){ }); // Step 2 Controller myApp.controller('SecondCtrl',Data ){ $scope.FirstName = Data.FirstName; });
任何帮助是极大的赞赏。
一个简单的解决方案是让你的工厂返回一个对象,并让你的控制器引用同一个对象:
原文链接:https://www.f2er.com/angularjs/147931.htmlJS:
// declare the app with no dependencies var myApp = angular.module('myApp',[]); // Create the factory that share the Fact myApp.factory('Fact',function(){ return { Field: '' }; }); // Two controllers sharing an object that has a string in it myApp.controller('FirstCtrl',Fact ){ $scope.Alpha = Fact; }); myApp.controller('SecondCtrl',Fact ){ $scope.Beta = Fact; });
HTML:
<div ng-controller="FirstCtrl"> <input type="text" ng-model="Alpha.Field"> First {{Alpha.Field}} </div> <div ng-controller="SecondCtrl"> <input type="text" ng-model="Beta.Field"> Second {{Beta.Field}} </div>
当应用程序变得更大,更复杂和更难以测试时,您可能不想以这种方式从工厂暴露整个对象,而是通过getter和setter提供有限的访问权限:
myApp.factory('Data',function () { var data = { FirstName: '' }; return { getFirstName: function () { return data.FirstName; },setFirstName: function (firstName) { data.FirstName = firstName; } }; });
使用这种方法,由消费控制器使用新值更新工厂,并监视更改以获得它们:
myApp.controller('FirstCtrl',function ($scope,Data) { $scope.firstName = ''; $scope.$watch('firstName',function (newValue,oldValue) { if (newValue !== oldValue) Data.setFirstName(newValue); }); }); myApp.controller('SecondCtrl',Data) { $scope.$watch(function () { return Data.getFirstName(); },oldValue) { if (newValue !== oldValue) $scope.firstName = newValue; }); });
HTML:
<div ng-controller="FirstCtrl"> <input type="text" ng-model="FirstName"> <br>Input is : <strong>{{FirstName}}</strong> </div> <hr> <div ng-controller="SecondCtrl"> Input should also be here: {{FirstName}} </div>