json 将变量从视图传递给另一个控制器 AngularJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25494324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:30:26  来源:igfitidea点击:

Pass Variable from View to another controller AngularJS

jsonfacebookangularjsionic-framework

提问by Gustavo Carre?o Salazar

I have one controller that gets an object with albums from facebook api.

我有一个控制器,它从 facebook api 获取一个带有专辑的对象。

.controller('GalleryCtrl', function($scope, $http) {
    $http.get('https://graph.facebook.com/v2.0/130180763686565/albums?fields=id,type,name,cover_photo,description&access_token=TOKEN').
        success(function(datos) {
            $scope.galleries = datos.data;
        })

})

})

In my view I print it like this,

在我看来,我是这样打印的,

<div ng-app="faceBook">
<div class="list" ng-repeat="gallery in galleries" ng-if="gallery.type=='normal'">

    <a class="item item-thumbnail-left" href="#/app/gallery/{{gallery.id}}" ng-click="$rootScope.albumId = {{gallery.id}}">
        <img src="https://graph.facebook.com/{{gallery.id}}/picture?type=album">
        <h2>{{gallery.name}}</h2>
        <p>{{gallery.description}}</p>
    </a>

</div>

What I need is to asign every Album the ID of the object (gallery.id) and send it to the next controller, to be able to download the pictures of that album.

我需要的是为每个相册分配对象的ID(gallery.id)并将其发送到下一个控制器,以便能够下载该相册的图片。

Send the gallery.id to this controller to put hte varible inside the http.get shown below where albumId is.

将gallery.id 发送到该控制器,将hte 变量放入如下所示的http.get 中,其中albumId 所在的位置。

How can I send the variable of the item clicked, from the first controller to the second?

如何将单击的项目的变量从第一个控制器发送到第二个控制器?

This is my Single Album Controller

这是我的单曲专辑控制器

.controller('AlbumCtrl', function($scope, $http) {
    $http.get('https://graph.facebook.com/v2.0/'+albumId+'/photos?fields=id&access_token=TOKEN').
        success(function(datos) {
            $scope.albums = datos.data;
        })

})

})

回答by Jeremy Wilken

There are different opinions about how to do this, as there are several approaches. Let me outline them briefly for you. I would primarily use a service, then $rootScope, and lastly events.

关于如何做到这一点有不同的意见,因为有几种方法。让我为您简要概述它们。我将主要使用服务,然后是 $rootScope,最后是事件。

Use services

使用服务

Services are Javascript objects that can be passed around using Angular's dependency injection. Just like you can request $http in your controller, you could create a service that would be able to exist anywhere DI works. This is the best approach (IMO) because you isolate your data into the service and are able to use DI to pass it around easily. The object doesn't have to just contain data, it can have methods which can reduce code duplication. The only negative I can think of is having create a new file.

服务是可以使用 Angular 的依赖注入传递的 Javascript 对象。就像您可以在控制器中请求 $http 一样,您可以创建一个可以存在于 DI 工作的任何地方的服务。这是最好的方法 (IMO),因为您将数据隔离到服务中,并且能够使用 DI 轻松传递它。对象不必只包含数据,它还可以具有可以减少代码重复的方法。我能想到的唯一缺点是创建了一个新文件。

This example is not ideal or work in all situations, you should adapt it as necessary. This example is only able to load the albums once when the service is first injected, and stores the data for any to use. Generally I make more complex services that can manage the data so my controllers don't have to manipulate my models.

此示例并不理想或适用于所有情况,您应该根据需要对其进行调整。这个例子只能在第一次注入服务时加载一次专辑,并存储数据以供任何人使用。通常我会制作更复杂的服务来管理数据,这样我的控制器就不必操纵我的模型。

Service

服务

angular.module('App').factory('AlbumService', function ($http) {

  var AlbumService;

  // Make our $http request and assign response to service
  $http.get('https://graph.facebook.com/v2.0/1234567890/albums?fields=id,type,name,cover_photo,description&access_token=TOKEN')
    .success(function(response) {
      AlbumService = response.data;
    });
  };

  return AlbumService;
});

Controller 1

控制器 1

angular.module('App').controller('OneCtrl', function ($scope, AlbumService) {
  // Assume this runs first, it will create the service and make the http 
  // request and be made available to the $scope
  $scope.albums = AlbumService;
});

Controller 2

控制器 2

angular.module('App').controller('TwoCtrl', function ($scope, AlbumService) {
  // Assume this runs second, it will return the same data from above. 
  // Even if it runs first, the result is the same because the first to inject 
  // the AlbumService will execute the $http request once and reuse the data
  console.log(AlbumService); 
});

Use $rootScope to share

使用 $rootScope 共享

You can assign anything to $rootScopeand get to it from any controller, directive, service, and most places (a few exceptions like app.config). This is handy and requires very little overhead. On the flip side, it kinda abuses your $rootScope and if you happen to use the same property name on $scope elsewhere you can have values get lost or overridden unintentionally.

您可以$rootScope从任何控制器、指令、服务和大多数地方(少数例外,如 app.config)分配任何内容并从它获取任何内容。这很方便并且只需要很少的开销。另一方面,它有点滥用您的 $rootScope 并且如果您碰巧在其他地方的 $scope 上使用相同的属性名称,您可能会无意中丢失或覆盖值。

Controller 1

控制器 1

angular.module('App').controller('OneCtrl', function ($rootScope, $http) {
  $http.get('https://graph.facebook.com/v2.0/1234567890/albums?fields=id,type,name,cover_photo,description&access_token=TOKEN')
    .success(function(response) {
      $rootScope.items = response.data;
    });
});

Controller 2

控制器 2

angular.module('App').controller('TwoCtrl', function ($scope) {
  // will log out the values from response.data above, since its not on 
  // $scope it travels up the scope tree until the $rootScope. 
  console.log($scope.items); 
});

Custom events

自定义事件

You can use events to broadcast (down the scope tree) or emit (up the scope tree) data. It's conceptually the same idea as listening to the domreadyevent before you use JavaScript. The benefits are you don't use $rootScopeand you can control if you send data up or down the scope tree (depending on what scopes need to know about this data). On the other hand, events can be tricky and cause confusion about causality as well as creating a dependency between various parts of the application that can make it difficult to maintain. In this example, both controllers also have to be in the same page for both the $broadcast and $on to be active.

您可以使用事件来广播(沿作用域树向下)或发出(沿作用域树向上)数据。这在概念上与domready在使用 JavaScript 之前侦听事件相同。好处是您不使用,$rootScope并且您可以控制是向上还是向下发送数据到作用域树(取决于哪些作用域需要了解这些数据)。另一方面,事件可能很棘手,会导致对因果关系的混淆,并在应用程序的各个部分之间创建依赖关系,从而使其难以维护。在这个例子中,两个控制器也必须在同一个页面中才能使 $broadcast 和 $on 处于活动状态。

Opinion: I would avoid this approach in most cases. One example where it might work is if you have a custom directive controlling an outside library (such as a chart) and you need to trigger the chart to change when events occur. I would use it when you need event driven, which is different from the original question about how to access data in different controllers (I would call that model driven).

意见:在大多数情况下,我会避免这种方法。它可能起作用的一个示例是,如果您有一个自定义指令控制外部库(例如图表),并且您需要在事件发生时触发图表进行更改。当您需要事件驱动时,我会使用它,这与关于如何在不同控制器中访问数据的原始问题不同(我称之为模型驱动)。

Controller 1

控制器 1

angular.module('App').controller('OneCtrl', function ($rootScope, $http) {
  // This will broadcast this event down through every scope from the top
  $http.get('https://graph.facebook.com/v2.0/1234567890/albums?fields=id,type,name,cover_photo,description&access_token=TOKEN')
    .success(function(response) {
      $rootScope.$broadcast('myCustomEvent', response.data);
    });
});

Controller 2

控制器 2

angular.module('App').controller('TwoCtrl', function ($scope) {
  // will log out the value of response.data above when the $broadcast occurs
  $scope.$on('myCustomEvent', function (event, data) {
    console.log(data);
  }); 
});

回答by Jo?o Paulo Motta

You should provide more information about your problem:

您应该提供有关您的问题的更多信息:

From what I understand this is what you are trying to do.

据我所知,这就是你想要做的。

Change your href call to ng-href and remove the ng-click.

将您的 href 调用更改为 ng-href 并删除 ng-click。

This:

这个:

  <a class="item item-thumbnail-left" href="#/app/gallery/{{gallery.id}}" ng-click="$rootScope.albumId = {{gallery.id}}">

Becomes this

变成这个

<a class="item item-thumbnail-left" ng-href="/app/gallery/{{gallery.id}}">

In the controller that will deal with the view. Suppose you'll call it ViewAlbumCtrl.

在将处理视图的控制器中。假设您将其命名为 ViewAlbumCtrl。

.controller('ViewAlbumCtrl', function($scope, $http, $routeParams) {
    var theId = $routeParams.galleryId;
    //Your cool code
});

And where you configure your routes you should have:

在你配置路由的地方,你应该有:

.config(['$routeProvider', 
  function($routeProvider) {
    $routeProvider
      .when('/app/gallery/:galleryId', {
        templateUrl: '/path/to/your/view.html',
        controller: 'ViewAlbumCtrl'
      });
   }]);

Hope it helps you.

希望对你有帮助。

回答by Joaquín Crippa

Use $stateParams!

使用 $stateParams!

In your app.js file

在你的 app.js 文件中

.state('app.single', {
url: "/clientes/:clienteId",
views: {
  'menuContent': {
    templateUrl: "views/cliente.html",
    controller: 'ClienteCtrl'
  }
}
})

Inside your view:

在您的视图中:

<ion-item class="item-avatar" href="#/app/clientes/{{cliente.id}}" >

The controller:

控制器:

angular.module('cobranza-mobile.controllers').
controller('ClienteCtrl', function ($scope, $stateParams) {
   alert($stateParams.clienteId);
});

回答by Luca Anceschi

You can send a message at $rootScope level from controller A and intercept it in controller B.

您可以从控制器 A 在 $rootScope 级别发送消息并在控制器 B 中拦截它。

  1. Inject $rootScope service into controller A.

  2. Broadcast the message and parameter[s] from controller A:

    $rootScope.$broadcast('userDefinedEvent', {parameterOne: 'stringValue'});

  3. Intercept it in controller B and take action accordingly:

    $scope.$on('userDefinedEvent', function (event, data) { console.log(data); });

  1. 将 $rootScope 服务注入控制器 A。

  2. 从控制器 A 广播消息和参数[s]:

    $rootScope.$broadcast('userDefinedEvent', {parameterOne: 'stringValue'});

  3. 在控制器 B 中拦截它并采取相应的行动:

    $scope.$on('userDefinedEvent', function (event, data) { console.log(data); });

Hope it'd help you.

希望对你有帮助。

Cheers, Luca

干杯,卢卡