[英]MVC view button click event , Pass AngularJs object to another MVC Controller
当视图上的按钮单击事件时,我必须将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;}
现在我只传递一个值。 我想将酒店 对象作为参数传递。 他们是这样做的吗?
您可以将整个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>
Two.html
<body ng-app="app"> <span> Recieved : {{message}}</span> </body>
$state.go('toState',object);
如果使用的是ui-router
则可以使用$state.go
将对象值发送到另一个控制器;如果不使用ui-router
则可以使用发射和广播。请参见此处的详细信息。
广播的工作plnkr可以在这里找到
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});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.