当视图上的按钮单击事件时,我必须将AngularJs对象传递给另一个Controller。
CHTML
<div ng-repeat="hotel in respData.hotels">
<button type="button" class="btn" data-ng-click="setTab(hotel.code)">Check Availability
</button></div>
脚本
$scope.setTab = function (hotelcode) {
var url = 'Hotel';
url += '?HotelCode=' + hotelcode '
window.location.href = url;}
现在我只传递一个值。我想将酒店 对象作为参数传递。 他们是这样做的吗?
答案 0 :(得分:2)
您可以将整个Hotel对象传递给第一个控制器,然后使用$ emit或$ broadcast将该对象发送到另一个控制器。这是一个简短的例子:
One.html
<html ng-app="app">
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script>
var app = angular.module('app', ['ui.router']).config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('two',{
url: '/two',
templateUrl: "two.html",
})
})
app.controller("Parent", function ($scope, $state) {
$scope.send = function (msg) {
$scope.$broadcast('eventName', { message: msg });
$state.go('two')
};
});
app.controller("Child", function ($scope) {
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
console.log($scope.message);
});
});
</script>
<body ng-app="app">
<h1> Index Page </h1>
<!---
Look at these div tags here, $broadcast is used to transfer content from
Parent to Child Controllers only and $emit for Child to Parent Controller
!--->
<div ng-controller = "Parent" >
<button ng-click = send('Hello')> Send Hello</button>
<div ng-controller = "Child" class="container" ui-view> </div>
</div>
</body>
</html>
&#13;
Two.html
<body ng-app="app">
<span> Recieved : {{message}}</span>
</body>
&#13;
答案 1 :(得分:1)
$state.go('toState',object);
如果您使用$state.go
,可以使用ui-router
将对象值发送到另一个控制器,否则您可以使用发射和广播查看详细信息here
可以找到广播的工作plnkr here
app.controller('Parent', function($scope) {
$scope.message="";
$scope.emitedmessage="";
$scope.clickevent=function(){
$scope.$broadcast('transfer',{message:$scope.message});
}
$scope.$on('transferUp',function(event,data){
console.log('on working');
$scope.emitedmessage=data.message;
});
});
app.controller('Child',function($scope){
$scope.message="";
$scope.broadcastmessage=""
$scope.$on('transfer',function(event,data){
$scope.broadcastmessage=data.message;
});
$scope.clickevent=function(){
$scope.$emit('transferUp',{message:$scope.message});
}
});