我想从另一个控制器访问模型date
的值,并在json对象中发出传递此值的请求。但是此ng-model
位于控制器DateParseCtrl
的范围内,而此controller
位于另一个名为mainController
的控制器内。如何访问此值并从mainController
传递给json对象? Ps:我只想从date
得到mainController
值。
的index.html
<body ng-controller='mainController'>
<datepicker date-format="dd/MM/yyyy" selector="form-control"
ng-controller='DateParserController'>
<input type="text" uib-datepicker-popup="{{ format }}"
ng-model='date' ng-blur='getSomething()'/>
</datepicker>
</body>
日期解析-ctrl.js
angular.module('myApp')
.controller('DateParserCtrl', function($scope, uibDateParser){
$scope.format = 'dd/MM/yyyy';
$scope.date = new Date();
});
mainController
angular.module('myApp')
.controller('mainController', function($scope, $http){
var date = $scope.date;
$scope.getSomething = function(){
$http({
method: 'POST',
url: 'url',
data: {date: date}
})
}
});
答案 0 :(得分:1)
有事件
日期解析-ctrl.js
angular.module('myApp')
.controller('DateParserCtrl', function($scope,$rootScope, uibDateParser){
$scope.format = 'dd/MM/yyyy';
$scope.date = new Date();
var dat=$scope.data;
$rootScope.$broadcast('sendDate',dat)
});
mainController
angular.module('myApp')
.controller('mainController', function($scope, $http){
$scope.$on('sendDate',function(event,data){
$scope.dateFromCtrl=data;
})
$scope.getSomething = function(){
$http({
method: 'POST',
url: 'url',
data: {date: $scope.dateFromCtrl}
})
}
});
答案 1 :(得分:1)
另一种方法是将日期作为getSomething
函数的参数提供:
<body ng-controller='mainController'>
<datepicker date-format="dd/MM/yyyy" selector="form-control"
ng-controller='DateParserController'>
<input type="text" uib-datepicker-popup="{{ format }}"
ng-model='date' ̶n̶g̶-̶b̶l̶u̶r̶=̶'̶g̶e̶t̶S̶o̶m̶e̶t̶h̶i̶n̶g̶(̶)̶'̶
ng-blur='getSomething(date)' />
</datepicker>
</body>
然后在主控制器中使用该参数:
angular.module('myApp')
.controller('mainController', function($scope, $http){
̶v̶a̶r̶ ̶d̶a̶t̶e̶ ̶=̶ ̶$̶s̶c̶o̶p̶e̶.̶d̶a̶t̶e̶;̶
̶$̶s̶c̶o̶p̶e̶.̶g̶e̶t̶S̶o̶m̶e̶t̶h̶i̶n̶g̶ ̶=̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶(̶)̶{̶
$scope.getSomething = function(date){
$http({
method: 'POST',
url: 'url',
data: {date: date}
})
}
});