本文介绍了两个控制器之间的角度关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在两个控制器之间共享角度值.我的方案有两个控制器和一个服务.当用户单击按钮时,第一个控制器必须创建一个随机数并将其传递给另一个控制器.
How to share values between two controllers in angular. My scenario has two controllers and one service. When the user clicks on a button a first controller must create a random number and pass it to another controller.
这是我的示例代码:
var app = angular.module('app', []);
app.controller("FirstController", function ($scope,sharedDateRange)
{
$scope.test = function(){
sharedDateRange.setData();
}
});
app.controller("SecondController", function ($scope,sharedDateRange) {
var data=[];
data = sharedDateRange.getData();
alert(data);
});
app.service('sharedDateRange', function ($http) {
var data=[];
return {
setData: function () {
data = Math.floor(Math.random() * 6) + 1;
}
,
getData: function(){
return data;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="FirstController">
<button ng-click="test()"> Click</button>
</div>
<div ng-controller="SecondController">
<span>{{data}}</span>
</div>
</div>
推荐答案
您的意思是当值更改时,第二个控制器必须获取新值吗?我使用$broadcast and $on
.
Did you mean that when the value has change, The 2nd controller must get the new value? I use $broadcast and $on
for it.
app.controller("FirstController", function ($scope,$rootScope,sharedDateRange)
{
$scope.test = function(){
sharedDateRange.setData();
$rootScope.$broadcast('changeValue');
}
});
app.controller("SecondController", function ($scope,sharedDateRange) {
var data=[];
data = sharedDateRange.getData();
$scope.data = data;
var cleanup = $scope.$on('changeValue', function() {
console.log("get");
$scope.data = sharedDateRange.getData();
})
//make sure to destroy to avoid memory leaks
$scope.$on('$destroy', cleanup);
});
html:
<div ng-controller="FirstController">
<button ng-click="test()">create random number</button>
</div>
<div ng-controller="SecondController">
{{data}}
</div>
工作演示此处
这篇关于两个控制器之间的角度关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!