I have a basic controller that displays my products,
我有一个显示产品的基本控制器,
App.controller('ProductCtrl',function($scope,$productFactory){
$productFactory.get().success(function(data){
$scope.products = data;
});
});
In my view I'm displaying this products in a list
在我的视图中,我将在列表中显示这些产品
<ul>
<li ng-repeat="product as products">
{{product.name}}
</li>
</ul
What I'm trying to do is when someone click on the product name, i have another view named cart where this product is added.
我要做的是,当有人点击产品名称时,我有一个名为cart的视图,其中添加了这个产品。
<ul class="cart">
<li>
//click one added here
</li>
<li>
//click two added here
</li>
</ul>
So my doubt here is, how do pass this clicked products from first controller to second? i assumed that cart should be a controller too.
我的疑问是,如何将点击的产品从第一个控制器传递到第二个控制器?我认为cart也应该是一个控制器。
I handle click event using directive. Also i feel i should be using service to achieve above functionality just can't figure how? because cart will be predefined number of products added could be 5/10 depending on which page user is. So i would like to keep this generic.
我使用指令处理点击事件。我也觉得我应该用服务来实现上面的功能只是无法想象如何?因为cart将是预定义的产品添加数量可以是5/10,这取决于页面用户。所以我想保留这个通用的。
Update:
更新:
I created a service to broadcast and in the second controller i receive it. Now the query is how do i update dom? Since my list to drop product is pretty hardcoded.
我创建了一个广播服务,并在第二个控制器中接收它。现在的问题是如何更新dom?因为我的产品列表是硬编码的。
18 个解决方案
#1
312
From the description, seems as though you should be using a service. Check out http://egghead.io/lessons/angularjs-sharing-data-between-controllers and AngularJS Service Passing Data Between Controllers to see some examples.
从描述来看,似乎您应该使用服务。看看http://egghead。控制器和AngularJS服务之间通过数据之间传递数据来查看一些示例。
You could define your product service as such:
你可以这样定义你的产品服务:
app.service('productService', function() {
var productList = [];
var addProduct = function(newObj) {
productList.push(newObj);
};
var getProducts = function(){
return productList;
};
return {
addProduct: addProduct,
getProducts: getProducts
};
});
Dependency inject the service into both controllers.
依赖项将服务注入两个控制器。
In your ProductController
, define some action that adds the selected object to the array:
在您的ProductController中,定义一些将所选对象添加到数组的操作:
app.controller('ProductController', function($scope, productService) {
$scope.callToAddToProductList = function(currObj){
productService.addProduct(currObj);
};
});
In your CartController
, get the products from the service:
在您的CartController中,从服务中获取产品:
app.controller('CartController', function($scope, productService) {
$scope.products = productService.getProducts();
});
#2
65
how do pass this clicked products from first controller to second?
如何将单击的产品从第一个控制器传递到第二个控制器?
On click you can call method that invokes broadcast:
点击后可以调用调用调用广播的方法:
$rootScope.$broadcast('SOME_TAG', 'your value');
and the second controller will listen on this tag like:
第二个控制器会监听这个标签:
$scope.$on('SOME_TAG', function(response) {
// ....
})
Since we can't inject $scope into services, there is nothing like a singleton $scope.
因为我们不能将$scope注入到服务中,所以没有什么比得上单例$scope。
But we can inject $rootScope
. So if you store value into the Service, you can run $rootScope.$broadcast('SOME_TAG', 'your value');
in the Service body. (See @Charx description about services)
但是我们可以注入$rootScope。因此,如果将值存储到服务中,可以运行$rootScope。广播美元(“SOME_TAG”、“你的价值”);在服务的身体。(见@Charx关于服务的描述)
app.service('productService', function($rootScope) {/*....*/}
Please check good article about $broadcast, $emit
请检查好的文章关于$broadcast, $emit
#3
25
Solution without creating Service, using $rootScope:
没有创建服务的解决方案,使用$rootScope:
To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.
要跨应用程序控制器共享属性,可以使用角度$rootScope。这是共享数据的另一种选择,将其放置以便人们了解它。
The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.
跨控制器共享某些功能的首选方式是服务,读取或更改可以使用$rootscope的全局属性。
var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showBanner = true;
}]);
app.controller('Ctrl2', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showBanner = false;
}]);
Using $rootScope in a template (Access properties with $root):
在模板中使用$rootScope(使用$root访问属性):
<div ng-controller="Ctrl1">
<div class="banner" ng-show="$root.showBanner"> </div>
</div>
#4
16
You can do this by two methods.
你可以用两种方法来做。
-
By using
$rootscope
, but I don't reccommend this. The$rootScope
is the top-most scope. An app can have only one$rootScope
which will be shared among all the components of an app. Hence it acts like a global variable.通过使用$rootscope,但是我不推荐它。$rootScope是最高的范围。一个应用程序只能有一个$rootScope,它将在一个应用程序的所有组件*享,因此它就像一个全局变量。
-
Using services. You can do this by sharing a service between two controllers. Code for service may look like this:
使用服务。您可以通过在两个控制器之间共享服务来实现这一点。服务代码如下:
app.service('shareDataService', function() { var myList = []; var addList = function(newObj) { myList.push(newObj); } var getList = function(){ return myList; } return { addList: addList, getList: getList }; });
You can see my fiddle here.
你可以看到我的小提琴。
#5
9
An even simpler way to share the data between controllers is using nested data structures. Instead of, for example
在控制器之间共享数据的一种更简单的方法是使用嵌套数据结构。例如,而不是
$scope.customer = {};
we can use
我们可以使用
$scope.data = { customer: {} };
The data
property will be inherited from parent scope so we can overwrite its fields, keeping the access from other controllers.
数据属性将从父范围继承,因此我们可以覆盖它的字段,保持对其他控制器的访问。
#6
8
angular.module('testAppControllers', [])
.controller('ctrlOne', function ($scope) {
$scope.$broadcast('test');
})
.controller('ctrlTwo', function ($scope) {
$scope.$on('test', function() {
});
});
#7
4
I saw the answers here, and it is answering the question of sharing data between controllers, but what should I do if I want one controller to notify the other about the fact that the data has been changed (without using broadcast)? EASY! Just using the famous visitor pattern:
我在这里看到了答案,它回答了在控制器之间共享数据的问题,但是如果我想让一个控制器通知另一个关于数据已经被更改的事实(不使用广播),我应该怎么做?简单!使用著名的访问者模式:
myApp.service('myService', function() {
var visitors = [];
var registerVisitor = function (visitor) {
visitors.push(visitor);
}
var notifyAll = function() {
for (var index = 0; index < visitors.length; ++index)
visitors[index].visit();
}
var myData = ["some", "list", "of", "data"];
var setData = function (newData) {
myData = newData;
notifyAll();
}
var getData = function () {
return myData;
}
return {
registerVisitor: registerVisitor,
setData: setData,
getData: getData
};
}
myApp.controller('firstController', ['$scope', 'myService',
function firstController($scope, myService) {
var setData = function (data) {
myService.setData(data);
}
}
]);
myApp.controller('secondController', ['$scope', 'myService',
function secondController($scope, myService) {
myService.registerVisitor(this);
this.visit = function () {
$scope.data = myService.getData();
}
$scope.data = myService.getData();
}
]);
In this simple manner, one controller can update another controller that some data has been updated.
用这种简单的方式,一个控制器可以更新另一个控制器,一些数据已经更新。
#8
4
we can store data in session and can use it anywhere in out program.
我们可以在会话中存储数据,并可以在程序的任何地方使用它。
$window.sessionStorage.setItem("Mydata",data);
Other place
其他地方
$scope.data = $window.sessionStorage.getItem("Mydata");
#9
3
I've created a factory that controls shared scope between route path's pattern, so you can maintain the shared data just when users are navigating in the same route parent path.
我创建了一个工厂,该工厂控制路由路径模式之间的共享范围,因此您可以在用户导航到相同的路由父路径时维护共享数据。
.controller('CadastroController', ['$scope', 'RouteSharedScope',
function($scope, routeSharedScope) {
var customerScope = routeSharedScope.scopeFor('/Customer');
//var indexScope = routeSharedScope.scopeFor('/');
}
])
So, if the user goes to another route path, for example '/Support', the shared data for path '/Customer' will be automatically destroyed. But, if instead of this the user goes to 'child' paths, like '/Customer/1' or '/Customer/list' the the scope won't be destroyed.
因此,如果用户访问另一个路径,例如'/Support',那么路径'/Customer'的共享数据将被自动销毁。但是,如果用户不使用“child”路径,比如“/Customer/1”或“/Customer/list”,那么这个范围就不会被破坏。
You can see an sample here: http://plnkr.co/edit/OL8of9
您可以在这里看到一个示例:http://plnkr.co/edit/OL8of9
#10
2
Make a factory in your module and add a reference of the factory in controller and use its variables in the controller and now get the value of data in another controller by adding reference where ever you want
在模块中创建一个工厂,并在控制器中添加工厂的引用,并在控制器中使用它的变量,现在通过在任何需要的地方添加引用,在另一个控制器中获取数据的值
#11
2
I don't know if it will help anyone, but based on Charx (thanks!) answer I have created simple cache service. Feel free to use, remix and share:
我不知道它是否会帮助任何人,但基于Charx(谢谢!)的回答,我创建了简单的缓存服务。请随意使用、混音和分享:
angular.service('cache', function() {
var _cache, _store, _get, _set, _clear;
_cache = {};
_store = function(data) {
angular.merge(_cache, data);
};
_set = function(data) {
_cache = angular.extend({}, data);
};
_get = function(key) {
if(key == null) {
return _cache;
} else {
return _cache[key];
}
};
_clear = function() {
_cache = {};
};
return {
get: _get,
set: _set,
store: _store,
clear: _clear
};
});
#12
2
One way using angular service:
使用角度服务的一种方式:
var app = angular.module("home", []);
app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});
app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});
app.factory('ser1', function(){
return {o: ''};
});
<div ng-app='home'>
<div ng-controller='one'>
Type in text:
<input type='text' ng-model="inputText.o"/>
</div>
<br />
<div ng-controller='two'>
Type in text:
<input type='text' ng-model="inputTextTwo.o"/>
</div>
</div>
https://jsfiddle.net/1w64222q/
https://jsfiddle.net/1w64222q/
#13
1
FYI The $scope Object has the $emit, $broadcast, $on AND The $rootScope Object has the identical $emit, $broadcast, $on
FYI $scope对象有$emit、$broadcast、$on和$rootScope对象具有相同的$发出、$broadcast、$on。
read more about publish/subscribe design pattern in angular here
阅读更多关于发布/订阅设计模式的角度在这里
#14
1
There are three ways to do it,
有三种方法,
a) using a service
使用服务
b) Exploiting depending parent/child relation between controller scopes.
b)利用控制器作用域之间依赖的父/子关系。
c) In Angular 2.0 "As" keyword will be pass the data from one controller to another.
c)在角2.0“As”中,关键字将数据从一个控制器传递到另一个控制器。
For more information with example, Please check the below link :
如需了解更多示例信息,请查看以下链接:
http://www.learnit.net.in/2016/03/angular-js.html
http://www.learnit.net.in/2016/03/angular-js.html
#15
1
To improve the solution proposed by @Maxim using $broadcast, send data don't change
为了改进@Maxim提出的使用$broadcast的解决方案,发送数据不会改变
$rootScope.$broadcast('SOME_TAG', 'my variable');
but to listening data
但听数据
$scope.$on('SOME_TAG', function(event, args) {
console.log("My variable is", args);// args is value of your variable
})
#16
1
1
using $localStorage
app.controller('ProductController', function($scope, $localStorage) {
$scope.setSelectedProduct = function(selectedObj){
$localStorage.selectedObj= selectedObj;
};
});
app.controller('CartController', function($scope,$localStorage) {
$scope.selectedProducts = $localStorage.selectedObj;
$localStorage.$reset();//to remove
});
2
On click you can call method that invokes broadcast:
点击后可以调用调用调用广播的方法:
$rootScope.$broadcast('SOME_TAG', 'your value');
and the second controller will listen on this tag like:
$scope.$on('SOME_TAG', function(response) {
// ....
})
3
using $rootScope:
4
window.sessionStorage.setItem("Mydata",data);
$scope.data = $window.sessionStorage.getItem("Mydata");
5
One way using angular service:
使用角度服务的一种方式:
var app = angular.module("home", []);
app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});
app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});
app.factory('ser1', function(){
return {o: ''};
});
#17
0
var custApp = angular.module("custApp", [])
.controller('FirstController', FirstController)
.controller('SecondController',SecondController)
.service('sharedData', SharedData);
FirstController.$inject = ['sharedData'];
function FirstController(sharedData) {
this.data = sharedData.data;
}
SecondController.$inject['sharedData'];
function SecondController(sharedData) {
this.data = sharedData.data;
}
function SharedData() {
this.data = {
value: 'default Value'
}
}
First Controller
第一个控制器
<div ng-controller="FirstController as vm">
<input type=text ng-model="vm.data.value" />
</div>
Second Controller
第二个控制器
<div ng-controller="SecondController as vm">
Second Controller<br>
{{vm.data.value}}
</div>
#18
-1
I think the
我认为
best way
is to use $localStorage. (Works all the time)app.controller('ProductController', function($scope, $localStorage) {
$scope.setSelectedProduct = function(selectedObj){
$localStorage.selectedObj= selectedObj;
};
});
Your cardController will be
你的cardController会
app.controller('CartController', function($scope,$localStorage) {
$scope.selectedProducts = $localStorage.selectedObj;
$localStorage.$reset();//to remove
});
You can also add
你也可以加入
if($localStorage.selectedObj){
$scope.selectedProducts = $localStorage.selectedObj;
}else{
//redirect to select product using $location.url('/select-product')
}
#1
312
From the description, seems as though you should be using a service. Check out http://egghead.io/lessons/angularjs-sharing-data-between-controllers and AngularJS Service Passing Data Between Controllers to see some examples.
从描述来看,似乎您应该使用服务。看看http://egghead。控制器和AngularJS服务之间通过数据之间传递数据来查看一些示例。
You could define your product service as such:
你可以这样定义你的产品服务:
app.service('productService', function() {
var productList = [];
var addProduct = function(newObj) {
productList.push(newObj);
};
var getProducts = function(){
return productList;
};
return {
addProduct: addProduct,
getProducts: getProducts
};
});
Dependency inject the service into both controllers.
依赖项将服务注入两个控制器。
In your ProductController
, define some action that adds the selected object to the array:
在您的ProductController中,定义一些将所选对象添加到数组的操作:
app.controller('ProductController', function($scope, productService) {
$scope.callToAddToProductList = function(currObj){
productService.addProduct(currObj);
};
});
In your CartController
, get the products from the service:
在您的CartController中,从服务中获取产品:
app.controller('CartController', function($scope, productService) {
$scope.products = productService.getProducts();
});
#2
65
how do pass this clicked products from first controller to second?
如何将单击的产品从第一个控制器传递到第二个控制器?
On click you can call method that invokes broadcast:
点击后可以调用调用调用广播的方法:
$rootScope.$broadcast('SOME_TAG', 'your value');
and the second controller will listen on this tag like:
第二个控制器会监听这个标签:
$scope.$on('SOME_TAG', function(response) {
// ....
})
Since we can't inject $scope into services, there is nothing like a singleton $scope.
因为我们不能将$scope注入到服务中,所以没有什么比得上单例$scope。
But we can inject $rootScope
. So if you store value into the Service, you can run $rootScope.$broadcast('SOME_TAG', 'your value');
in the Service body. (See @Charx description about services)
但是我们可以注入$rootScope。因此,如果将值存储到服务中,可以运行$rootScope。广播美元(“SOME_TAG”、“你的价值”);在服务的身体。(见@Charx关于服务的描述)
app.service('productService', function($rootScope) {/*....*/}
Please check good article about $broadcast, $emit
请检查好的文章关于$broadcast, $emit
#3
25
Solution without creating Service, using $rootScope:
没有创建服务的解决方案,使用$rootScope:
To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.
要跨应用程序控制器共享属性,可以使用角度$rootScope。这是共享数据的另一种选择,将其放置以便人们了解它。
The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.
跨控制器共享某些功能的首选方式是服务,读取或更改可以使用$rootscope的全局属性。
var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showBanner = true;
}]);
app.controller('Ctrl2', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showBanner = false;
}]);
Using $rootScope in a template (Access properties with $root):
在模板中使用$rootScope(使用$root访问属性):
<div ng-controller="Ctrl1">
<div class="banner" ng-show="$root.showBanner"> </div>
</div>
#4
16
You can do this by two methods.
你可以用两种方法来做。
-
By using
$rootscope
, but I don't reccommend this. The$rootScope
is the top-most scope. An app can have only one$rootScope
which will be shared among all the components of an app. Hence it acts like a global variable.通过使用$rootscope,但是我不推荐它。$rootScope是最高的范围。一个应用程序只能有一个$rootScope,它将在一个应用程序的所有组件*享,因此它就像一个全局变量。
-
Using services. You can do this by sharing a service between two controllers. Code for service may look like this:
使用服务。您可以通过在两个控制器之间共享服务来实现这一点。服务代码如下:
app.service('shareDataService', function() { var myList = []; var addList = function(newObj) { myList.push(newObj); } var getList = function(){ return myList; } return { addList: addList, getList: getList }; });
You can see my fiddle here.
你可以看到我的小提琴。
#5
9
An even simpler way to share the data between controllers is using nested data structures. Instead of, for example
在控制器之间共享数据的一种更简单的方法是使用嵌套数据结构。例如,而不是
$scope.customer = {};
we can use
我们可以使用
$scope.data = { customer: {} };
The data
property will be inherited from parent scope so we can overwrite its fields, keeping the access from other controllers.
数据属性将从父范围继承,因此我们可以覆盖它的字段,保持对其他控制器的访问。
#6
8
angular.module('testAppControllers', [])
.controller('ctrlOne', function ($scope) {
$scope.$broadcast('test');
})
.controller('ctrlTwo', function ($scope) {
$scope.$on('test', function() {
});
});
#7
4
I saw the answers here, and it is answering the question of sharing data between controllers, but what should I do if I want one controller to notify the other about the fact that the data has been changed (without using broadcast)? EASY! Just using the famous visitor pattern:
我在这里看到了答案,它回答了在控制器之间共享数据的问题,但是如果我想让一个控制器通知另一个关于数据已经被更改的事实(不使用广播),我应该怎么做?简单!使用著名的访问者模式:
myApp.service('myService', function() {
var visitors = [];
var registerVisitor = function (visitor) {
visitors.push(visitor);
}
var notifyAll = function() {
for (var index = 0; index < visitors.length; ++index)
visitors[index].visit();
}
var myData = ["some", "list", "of", "data"];
var setData = function (newData) {
myData = newData;
notifyAll();
}
var getData = function () {
return myData;
}
return {
registerVisitor: registerVisitor,
setData: setData,
getData: getData
};
}
myApp.controller('firstController', ['$scope', 'myService',
function firstController($scope, myService) {
var setData = function (data) {
myService.setData(data);
}
}
]);
myApp.controller('secondController', ['$scope', 'myService',
function secondController($scope, myService) {
myService.registerVisitor(this);
this.visit = function () {
$scope.data = myService.getData();
}
$scope.data = myService.getData();
}
]);
In this simple manner, one controller can update another controller that some data has been updated.
用这种简单的方式,一个控制器可以更新另一个控制器,一些数据已经更新。
#8
4
we can store data in session and can use it anywhere in out program.
我们可以在会话中存储数据,并可以在程序的任何地方使用它。
$window.sessionStorage.setItem("Mydata",data);
Other place
其他地方
$scope.data = $window.sessionStorage.getItem("Mydata");
#9
3
I've created a factory that controls shared scope between route path's pattern, so you can maintain the shared data just when users are navigating in the same route parent path.
我创建了一个工厂,该工厂控制路由路径模式之间的共享范围,因此您可以在用户导航到相同的路由父路径时维护共享数据。
.controller('CadastroController', ['$scope', 'RouteSharedScope',
function($scope, routeSharedScope) {
var customerScope = routeSharedScope.scopeFor('/Customer');
//var indexScope = routeSharedScope.scopeFor('/');
}
])
So, if the user goes to another route path, for example '/Support', the shared data for path '/Customer' will be automatically destroyed. But, if instead of this the user goes to 'child' paths, like '/Customer/1' or '/Customer/list' the the scope won't be destroyed.
因此,如果用户访问另一个路径,例如'/Support',那么路径'/Customer'的共享数据将被自动销毁。但是,如果用户不使用“child”路径,比如“/Customer/1”或“/Customer/list”,那么这个范围就不会被破坏。
You can see an sample here: http://plnkr.co/edit/OL8of9
您可以在这里看到一个示例:http://plnkr.co/edit/OL8of9
#10
2
Make a factory in your module and add a reference of the factory in controller and use its variables in the controller and now get the value of data in another controller by adding reference where ever you want
在模块中创建一个工厂,并在控制器中添加工厂的引用,并在控制器中使用它的变量,现在通过在任何需要的地方添加引用,在另一个控制器中获取数据的值
#11
2
I don't know if it will help anyone, but based on Charx (thanks!) answer I have created simple cache service. Feel free to use, remix and share:
我不知道它是否会帮助任何人,但基于Charx(谢谢!)的回答,我创建了简单的缓存服务。请随意使用、混音和分享:
angular.service('cache', function() {
var _cache, _store, _get, _set, _clear;
_cache = {};
_store = function(data) {
angular.merge(_cache, data);
};
_set = function(data) {
_cache = angular.extend({}, data);
};
_get = function(key) {
if(key == null) {
return _cache;
} else {
return _cache[key];
}
};
_clear = function() {
_cache = {};
};
return {
get: _get,
set: _set,
store: _store,
clear: _clear
};
});
#12
2
One way using angular service:
使用角度服务的一种方式:
var app = angular.module("home", []);
app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});
app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});
app.factory('ser1', function(){
return {o: ''};
});
<div ng-app='home'>
<div ng-controller='one'>
Type in text:
<input type='text' ng-model="inputText.o"/>
</div>
<br />
<div ng-controller='two'>
Type in text:
<input type='text' ng-model="inputTextTwo.o"/>
</div>
</div>
https://jsfiddle.net/1w64222q/
https://jsfiddle.net/1w64222q/
#13
1
FYI The $scope Object has the $emit, $broadcast, $on AND The $rootScope Object has the identical $emit, $broadcast, $on
FYI $scope对象有$emit、$broadcast、$on和$rootScope对象具有相同的$发出、$broadcast、$on。
read more about publish/subscribe design pattern in angular here
阅读更多关于发布/订阅设计模式的角度在这里
#14
1
There are three ways to do it,
有三种方法,
a) using a service
使用服务
b) Exploiting depending parent/child relation between controller scopes.
b)利用控制器作用域之间依赖的父/子关系。
c) In Angular 2.0 "As" keyword will be pass the data from one controller to another.
c)在角2.0“As”中,关键字将数据从一个控制器传递到另一个控制器。
For more information with example, Please check the below link :
如需了解更多示例信息,请查看以下链接:
http://www.learnit.net.in/2016/03/angular-js.html
http://www.learnit.net.in/2016/03/angular-js.html
#15
1
To improve the solution proposed by @Maxim using $broadcast, send data don't change
为了改进@Maxim提出的使用$broadcast的解决方案,发送数据不会改变
$rootScope.$broadcast('SOME_TAG', 'my variable');
but to listening data
但听数据
$scope.$on('SOME_TAG', function(event, args) {
console.log("My variable is", args);// args is value of your variable
})
#16
1
1
using $localStorage
app.controller('ProductController', function($scope, $localStorage) {
$scope.setSelectedProduct = function(selectedObj){
$localStorage.selectedObj= selectedObj;
};
});
app.controller('CartController', function($scope,$localStorage) {
$scope.selectedProducts = $localStorage.selectedObj;
$localStorage.$reset();//to remove
});
2
On click you can call method that invokes broadcast:
点击后可以调用调用调用广播的方法:
$rootScope.$broadcast('SOME_TAG', 'your value');
and the second controller will listen on this tag like:
$scope.$on('SOME_TAG', function(response) {
// ....
})
3
using $rootScope:
4
window.sessionStorage.setItem("Mydata",data);
$scope.data = $window.sessionStorage.getItem("Mydata");
5
One way using angular service:
使用角度服务的一种方式:
var app = angular.module("home", []);
app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});
app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});
app.factory('ser1', function(){
return {o: ''};
});
#17
0
var custApp = angular.module("custApp", [])
.controller('FirstController', FirstController)
.controller('SecondController',SecondController)
.service('sharedData', SharedData);
FirstController.$inject = ['sharedData'];
function FirstController(sharedData) {
this.data = sharedData.data;
}
SecondController.$inject['sharedData'];
function SecondController(sharedData) {
this.data = sharedData.data;
}
function SharedData() {
this.data = {
value: 'default Value'
}
}
First Controller
第一个控制器
<div ng-controller="FirstController as vm">
<input type=text ng-model="vm.data.value" />
</div>
Second Controller
第二个控制器
<div ng-controller="SecondController as vm">
Second Controller<br>
{{vm.data.value}}
</div>
#18
-1
I think the
我认为
best way
is to use $localStorage. (Works all the time)app.controller('ProductController', function($scope, $localStorage) {
$scope.setSelectedProduct = function(selectedObj){
$localStorage.selectedObj= selectedObj;
};
});
Your cardController will be
你的cardController会
app.controller('CartController', function($scope,$localStorage) {
$scope.selectedProducts = $localStorage.selectedObj;
$localStorage.$reset();//to remove
});
You can also add
你也可以加入
if($localStorage.selectedObj){
$scope.selectedProducts = $localStorage.selectedObj;
}else{
//redirect to select product using $location.url('/select-product')
}