gpt4 book ai didi

javascript - 在 AngularJS Controller 之间共享数据

转载 作者:IT老高 更新时间:2023-10-28 11:03:33 25 4
gpt4 key购买 nike

我正在尝试跨 Controller 共享数据。用例是一个多步骤表单,在一个输入中输入的数据稍后会在原始 Controller 之外的多个显示位置使用。下方和 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', function( $scope, Data ){
$scope.FirstName = Data.FirstName;
});

非常感谢任何帮助。

最佳答案

一个简单的解决方案是让您的工厂返回一个对象并让您的 Controller 使用对同一对象的引用:

JS:

// 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', function( $scope, Fact ){
$scope.Alpha = Fact;
});

myApp.controller('SecondCtrl', function( $scope, 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>

演示: http://jsfiddle.net/HEdJF/

当应用程序变得更大、更复杂且更难测试时,您可能不想以这种方式从工厂公开整个对象,而是提供有限的访问权限,例如通过 getter 和 setter:

myApp.factory('Data', function () {

var data = {
FirstName: ''
};

return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (firstName) {
data.FirstName = firstName;
}
};
});

使用这种方法,由消费 Controller 使用新值更新工厂,并观察更改以获取它们:

myApp.controller('FirstCtrl', function ($scope, Data) {

$scope.firstName = '';

$scope.$watch('firstName', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setFirstName(newValue);
});
});

myApp.controller('SecondCtrl', function ($scope, Data) {

$scope.$watch(function () { return Data.getFirstName(); }, function (newValue, 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>

演示: http://jsfiddle.net/27mk1n1o/

关于javascript - 在 AngularJS Controller 之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21919962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com