簡體   English   中英

MVC視圖按鈕單擊事件,將AngularJs對象傳遞給另一個MVC控制器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM