![](/img/trans.png)
[英]In AngularJS, how can one controller get data being filtered from another controller
[英]How to get data dynamically from one controller to another in angularjs?
.controller('Ctrl1', function($scope, $http) {
$scope.langChecked = function(){
$scope.value = $('input[name=lang-check]:checked').val();
console.log($scope.value);
};
})
.controller('Ctrl2', function($scope, $http, $state, Scopes) {
if($scope.value='something'){
alert('scope passed');
}
});
我嘗試使用rootscope並在控制器之間傳遞值
.run(function ($rootScope) {
$rootScope.$on('scope.stored', function (event, data) {
console.log("scope.stored", data);
});
})
.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
但我的ctrl2頁面在刷新時首先加載,當我使用時它會出錯
Scopes.get('Ctrl1').value;
在Ctrl2中。 請幫忙
你必須用$rootscope
注入你的工廠。
工廠無法訪問當前的控制器/指令范圍,因為沒有。 他們確實可以訪問應用程序的根目錄,這就是$ rootScope可用的原因
.factory('Scopes',["$rootScope", function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
}]);
.factory('Authorization', function() {
authorization = {};
authorization.variable= '';
return authorization;
})
.controller('Ctrl1', function($scope, Authorization) {
$scope.input = Authorization;
console.log($scope.input.variable);
})
.controller('Ctrl2', function($scope, Authorization) {
$scope.input = Authorization;
console.log($scope.input.variable);
});
<input data-ng-controller="Ctrl1" type="text" ng-model="input.variable">
這對我有用。 謝謝你的答案:)我正在使用帶角度的離子。 使用工廠來存儲數據和獲取工作就像一個魅力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.