在AngularJS我如何通过控制器之间的变量与服务? [英] In AngularJS how do I pass variables between controllers with a service?
问题描述
我想通过控制器之间的变量与服务。这里是通过将变量(在此情况下,一首歌曲ID)的服务:
使用严格的;angular.module('PortalApp')
。服务('ActionbarService',['$窗口',功能ActionbarService(窗口){
VAR歌曲;
返回{
getSong:功能(){
返回歌曲;
},
setSong:函数(值){
歌=价值;
}
};
}]);
下面是控制器我从设定歌曲的相关部分:
$ scope.actionbarSetSong =功能(song_id){
ActionbarService.setSong(song_id);
}
和这里控制器我从获取歌曲ID:
使用严格的;angular.module('PortalApp')
.controller('ActionbarCtrl',函数($范围,MediaService,ActionbarService,$位置$ routeParams,AudioPlayerAPI){
$ scope.song_id = ActionbarService.getSong();
$ scope.openPlaylistModal =功能(song_id){ $(#addToPlaylist)模式(显示)。
}
});
这是在服务被设置,因为当我在我看来,做getSong它的工作(我忘了在哪里),但后来当我尝试将其设置为我的第二个控制器,这是行不通的。下面是我的参考视图的相关部分:
< DIV CLASS =单元行动吧NG点击=actionbarSetSong(song.id); NG-重复=歌media.data>
一些东西
< / DIV>
嗯..服务回报新ActionbarService
。你可能想使用工厂
,或者改变您的getter / setter方法为 this.get
&安培; this.set
。
此外,避免污染 $ rootScope
;只要你想控制器之间共享数据,使用服务。
I want to pass a variable between controllers with a service. Here is the service to pass the variable (in this case a song id):
'use strict';
angular.module('PortalApp')
.service('ActionbarService', ['$window', function ActionbarService(window) {
var song;
return {
getSong: function () {
return song;
},
setSong: function(value) {
song = value;
}
};
}]);
Here is the relevant part of the controller I am setting the song from:
$scope.actionbarSetSong = function(song_id) {
ActionbarService.setSong(song_id);
}
and here is the controller I am getting the song id from:
'use strict';
angular.module('PortalApp')
.controller('ActionbarCtrl', function ($scope, MediaService, ActionbarService, $location, $routeParams, AudioPlayerAPI) {
$scope.song_id = ActionbarService.getSong();
$scope.openPlaylistModal = function (song_id) {
$("#addToPlaylist").modal('show');
}
});
It is being set in the service because when I do getSong in my view it worked (I forget where), but then when I try to set it in my 2nd controller it doesn't work. Here's the relevant part of my view for reference:
<div class="cell action-bar" ng-click="actionbarSetSong(song.id);" ng-repeat="song in media.data">
Some Stuff
</div>
Mmm.. service returns new ActionbarService
. You probably want to use factory
, or change your getters/setters to this.get
& this.set
.
Also, avoid polluting the $rootScope
; whenever you want to share data between controllers, use a service.
这篇关于在AngularJS我如何通过控制器之间的变量与服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!