问题描述
大家好,我使用 angular js,我需要将值从一个页面控制器传输到另一个页面控制器,并将该值放入一个范围内,任何人都可以帮助我如何做到这一点
hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
$scope.Message="Hi welcome"
}]);
现在我想将范围消息显示到 page2 控制器中
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
///here i want get that scope value
}]);
推荐答案
使用服务将数据从一个控制器共享到另一个控制器
我们可以创建一个服务来set
和get
controllers
之间的数据,然后将该服务注入到我们想要的控制器函数中使用它.
We can create a service to set
and get
the data between the controllers
and then inject that service in the controller function where we want to use it.
服务:
app.service('setGetData', function() {
var data = '';
getData: function() { return data; },
setData: function(requestData) { data = requestData; }
});
控制器:
app.controller('Controller1', ['setGetData',function(setGetData) {
app.controller('Controller1', ['setGetData',function(setGetData) {
//从一个控制器设置数据$scope.Message="您好,欢迎";
setGetData.setData($scope.Message);
// To set the data from the one controller $scope.Message="Hi welcome";
setGetData.setData($scope.Message);
}]);
app.controller('Controller2', ['setGetData',function(setGetData) {
// To get the data from the another controller
var res = setGetData.getData();
console.log(res); // Hi welcome
}]);
这里,我们可以看到Controller1
用于设置数据,Controller2
用于获取数据.因此,我们可以像这样将数据从一个控制器共享到另一个控制器.
Here, we can see that Controller1
is used for setting the data and Controller2
is used for getting the data. So, we can share the data from one controller to another controller like this.
这篇关于如何使用angular js 1将数据从一个控制器传递到另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!