如何分享angularjs控制器之间的数据 [英] How to share data between controllers in angularjs
问题描述
目前,我正在努力学习angularJS时遇到了问题控制器之间的数据访问。
我的第一个控制器就会从我的API货币的名单,并将其分配给$ scope.currencies。当我点击编辑,有什么是应该发生的是,它切换它使用另一个控制器的看法。现在使用batarang调试时,$ scope.currencies确实显示货币对象的数组:
{
货币:[{
货币code:HKD
说明:港元
ExchangeRateModifier:* EXCHANGERATE:1
DecimalPlace:2
},{
货币code:USD
说明:美元
ExchangeRateModifier:* EXCHANGERATE:7.7
DecimalPlace:2
}]
}
但在使用时, angular.copy
的 $ scope.copiedcurrencies
结果无效。
函数CurrencyEditCtrl($范围,$喷油器,$ routeParams){
$ injector.invoke(CurrencyCtrl,对此,{$范围:$范围});
$ scope.copiedcurrencies = angular.copy($ scope.currencies);
的console.log($ scope.copiedcurrencies);
}
有关控制器之间共享数据的最常见和推荐的方法是使用一种服务。 点击这里在线演示(见app.js)
VAR应用= angular.module('对myApp',[]);app.factory('为myService',函数(){
VAR为myService = {
富:'棒'
};
返回为myService;
});app.controller('myCtrl1',函数(为myService){
的console.log(myService.foo);
myService.foo ='再也没有吧!;
});app.controller('myCtrl2',函数(为myService){
的console.log(myService.foo);
});
请注意:有创建服务的几种方法
。I'm currently trying to learn angularJS and am having trouble accessing data between controllers.
My first controller pulls a list of currencies from my api and assigns it to $scope.currencies. When I click edit, what is supposed to happen is that it switches the view which uses another controller. now when debugging using batarang, $scope.currencies does show an array of currency objects:
{
currencies: [{
CurrencyCode: HKD
Description: HONG KONG DOLLAR
ExchangeRateModifier: * ExchangeRate: 1
DecimalPlace: 2
}, {
CurrencyCode: USD
Description: US DOLLAR
ExchangeRateModifier: * ExchangeRate: 7.7
DecimalPlace: 2
}]
}
But when using angular.copy
, the $scope.copiedcurrencies
result in null.
function CurrencyEditCtrl($scope, $injector, $routeParams) {
$injector.invoke(CurrencyCtrl, this, { $scope: $scope });
$scope.copiedcurrencies = angular.copy($scope.currencies);
console.log($scope.copiedcurrencies);
}
The most common and recommended method for sharing data between controllers is to use a service. Click here for Live Demo (see app.js)
var app = angular.module('myApp', []);
app.factory('myService', function() {
var myService = {
foo: 'bar'
};
return myService;
});
app.controller('myCtrl1', function(myService) {
console.log(myService.foo);
myService.foo = 'not bar anymore!';
});
app.controller('myCtrl2', function(myService) {
console.log(myService.foo);
});
Note: there are several ways of creating a service.
这篇关于如何分享angularjs控制器之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!