[英]How do I pass value to different controller in Angular js
我正在使用角度框架,並嘗試將$ scope傳遞給應用程序中的其他控制器。
更新:
我的問題是,直到用戶單擊按鈕,我才能獲取$ scope數據。
.controller('firstCtrl', function($scope) {
$scope.getTest = function(){
$scope.test1 = 'good.'
$scope.test2 = 'bad.'
…..more
}
})
我需要將$ scope對象傳遞給其他控制器
.controller('secondCtrl', function($scope) {
console.log($scope.test1)
})
我該怎么做? 謝謝!
為了在兩個控制器之間共享數據,您需要使用factory 。
有關更多詳細信息,請觀看此視頻:John Lindquist撰寫的“ AngularJS視頻教程: 在控制器之間共享數據 ”。
要在控制器之間共享信息,請使用服務。 可以這樣創建服務:
//Create angular main app module
var app = angular.module('myApp', []);
//create a service
app.service('sharedService', function () {
this.test1 = [1, 2, 3, 4];
});
//one controller, injecting the service
app.controller('firstCtrl', function ($scope, sharedService) {
sharedService.test1[0] = 5;
console.log(sharedService.test1[0]) //5, 2, 3, 1
});
//two controller, injecting the same service
app.controller('secondCtrl', function ($scope, sharedService) {
sharedService.test[1] = 4;
console.log(sharedService.test1[0]) //5, 4, 3, 1
});
這是我剛剛在jsFiddle上創建的示例:
在$ rootScope上使用自定義事件
.controller('firstCtrl',['$rootScope', function($rootScope) {
$scope.getTest = function(){
$rootScope.your_object = {foo:bar}
$rootScope.$emit('custom_event');
}
}])
.controller('secondCtrl', function($scope,$rootScope) {
$rootScope.$on('custom_event',function(){
//do stuff
//$rootScope.your_object is available
})
});
如果控制器實例化的次數超過一次,則可能需要從該事件取消綁定根作用域
可能存在反對“污染”根范圍的異議,但這正是其目的所在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.