从View传递变量到另一个控制器AngularJS [英] Pass Variable from View to another controller AngularJS

查看:129
本文介绍了从View传递变量到另一个控制器AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,与专辑来自Facebook的API获取的对象。

I have one controller that gets an object with albums from 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>

我需要的是ASIGN每一张专辑的对象(gallery.id)的ID,并将其发送到下一个控制器,才能够下载相册中的照片。

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.

发送gallery.id到该控制器把兴田varible以下,其中ALBUMID显示在http.get内。

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

我如何发送项目的可变点击,从第一控制器到第二个?

这是我的单曲专辑控制器

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;
        })

})

推荐答案

有关于如何做到这一点不同意见,因为有几种方法。让我简单介绍一下它们。我将主要使用服务,那么$ rootScope,最后事件。

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.

服务是可以围绕采用了棱角分明的依赖注入传递JavaScript对象。就像你可以在你的控制器要求$ HTTP,您可以创建将能够在任何地方存在工程DI服务。这是最好的办法(IMO),因为你隔离你的数据到服务,并能够使用DI通过它很容易左右。对象不必只包含数据时,它可以具有能减少code复制的方法。我能想到的唯一的缺点是有创建一个新的文件。

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.

这个例子并不是在所有情况下的理想或工作,你应该把它作为必要的调整。本实施例是仅能够在首次注入的服务一次加载的相册,并存储用于任何使用的数据。一般来说,我做出更复杂的服务,可管理的数据,所以我的控制器没有操纵我的模型。

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.

服务

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;
});

控制器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;
});

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); 
});

使用$ rootScope分享

您可以指定任何 $ rootScope 并从任何控制器,指导,服务得到它,而大多数地方(有一些例外喜欢的app.config)。这是非常方便,需要非常小的开销。在另一面,它有点滥用你的$ rootScope,如果你碰巧使用在$范围相同的属性名称在其他地方,你可以有值丢失或无意地忽略。

Use $rootScope to share

You can assign anything to $rootScope and 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.

控制器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;
    });
});

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); 
});

自定义事件

您可以使用事件广播(向下范围树)或散发(最多范围树)的数据。这是概念上相同的想法,听 domready中事件使用JavaScript之前。好处是您不使用 $ rootScope ,如果你发送的数据向上或向下的范围树(根据需要知道这个数据什么范围),你可以控制的。另一方面,事件可以是棘手,并导致大约因果关系混乱以及创建应用程序,可以使难以维持各部分之间的依赖关系。在这个例子中,两个控制器也必须在同时为$广播同一网页和$上有活性

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 domready event before you use JavaScript. The benefits are you don't use $rootScope and 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.

意见:我会避免在大多数情况下,这种做法。其中一个例子,它可能工作是,如果你有一个自定义指令控制外部库(如图表),你需要触发图表事件发生时改变。当你需要事件驱动的,这是关于如何访问不同的控制器数据(我称之为模型驱动)原来的问题不同,我会用它。

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).

控制器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);
    });
});

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);
  }); 
});

这篇关于从View传递变量到另一个控制器AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆