javascript - Chia sẻ dữ liệu giữa các bộ điều khiển AngularJS
Tôi đang cố gắng chia sẻ dữ liệu giữa các controller. Trường hợp sử dụng là một biểu mẫu nhiều bước, dữ liệu nhập vào ở một trường sau đó được sử dụng ở nhiều vị trí hiển thị ngoài controller gốc. Mã bên dưới và trong jsfiddle đây.
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;
});
Bất cứ sự giúp đỡ nào cũng đều được đánh giá cao.
Câu trả lời #1
Một giải pháp đơn giản là để nhà máy của bạn trả về một đối tượng và cho các bộ điều khiển của bạn làm việc với một tham chiếu đến cùng một đối tượng:
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>
Demo: http://jsfiddle.net/HEdJF/
Khi các ứng dụng trở nên lớn hơn, phức tạp hơn và khó kiểm tra hơn, bạn có thể không muốn tiết lộ toàn bộ đối tượng từ nhà máy theo cách này, mà thay vào đó chỉ cung cấp quyền truy cập hạn chế, ví dụ thông qua các phương thức getter và setter:
myApp.factory('Data', function () {
var data = {
FirstName: ''
};
return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (firstName) {
data.FirstName = firstName;
}
};
});
Với phương pháp này, việc cập nhật nhà máy với các giá trị mới và theo dõi các thay đổi để lấy chúng phụ thuộc vào các bộ điều khiển sử dụng nó:
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>
Demo: http://jsfiddle.net/27mk1n1o/
Câu trả lời #2
Tôi thích không sử dụng $watch cho việc này. Thay vì gán toàn bộ dịch vụ cho phạm vi của controller, bạn có thể chỉ gán dữ liệu.
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>
Ngoài ra, bạn có thể cập nhật dữ liệu dịch vụ bằng phương pháp trực tiếp.
JS :
// A new factory with an update method
myApp.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 method
myApp.controller('SecondCtrl', function($scope, MyService){
$scope.data = MyService.data;
$scope.updateData = function(first, last) {
MyService.update(first, last);
}
});
Câu trả lời #3
Có nhiều cách bạn có thể chia sẻ dữ liệu giữa các bộ điều khiển
- sử dụng dịch vụ
- sử dụng dịch vụ $state.go
- sử dụng stateparams
- sử dụng rootscope
Giải thích về từng phương pháp:
Tôi sẽ không giải thích vì nó đã được ai đó giải thích rồi
sử dụng
$state.go$state.go('book.name', {Name: 'XYZ'}); // then get parameter out of URL $state.params.Name;$stateparamhoạt động theo cách tương tự như$state.go, bạn truyền nó như một đối tượng từ controller gửi và thu thập trong controller nhận sử dụng stateparamsử dụng
$rootscope(a) gửi dữ liệu từ bộ điều khiển con đến bộ điều khiển cha
$scope.Save(Obj,function(data) { $scope.$emit('savedata',data); //pass the data as the second parameter }); $scope.$on('savedata',function(event,data) { //receive the data as second parameter });(b) gửi dữ liệu từ bộ điều khiển cha sang bộ điều khiển con
$scope.SaveDB(Obj,function(data){ $scope.$broadcast('savedata',data); }); $scope.SaveDB(Obj,function(data){`enter code here` $rootScope.$broadcast('saveCallback',data); });
