如何强制父控制器重新加载数据?
How to force parent controller to reload data?
我试图在我更新他的子控制器中的数据后强制父控制器重新加载数据。
Html :
<div ng-controller='parentCtr'>
{{data}}
<mydirective></mydirective>
</div>
parentCtr 中的数据是通过这样调用服务从服务器获取的:
function parentCtr(){
$scope.data=someservice.getDate();
}
in mydirective: function childCtr(){
// do something to update data and save in the same server.
someservice.update(data);
}
我需要的是在 someservice.update() 成功后,我需要父级刷新数据并显示我的更新信息。
像这样调用服务
someService.update(data).then(function (response) {
recal funcation to load data
},
function (err) {})
尝试将函数传递到指令的范围。例如:
(function() {
'use strict';
angular
.module('myApp', []);
function myCtrl($scope){
$scope.controllerFn = function(){
console.log('Fired by directive');
};
}
function mydirective() {
return {
restrict: 'AE',
scope: {
parentFunction: '='
},
controller: function($scope, someservice) {
var data = {};
someservice
.update(data)
.then($scope.parentFunction, null);
}
};
}
angular
.module('myApp')
.controller('myCtrl', myCtrl)
.directive('mydirective', mydirective);
}());
<div ng-controller='myCtrl'>
<mydirective parent-function="controllerFn()"></mydirective>
</div>
你可以通过这种方式完成。调用成功发出消息,在父控制器中监听消息刷新状态或页面。
function parentCtr($scope,$state){
$scope.data=someservice.getDate();
$scope.$on('refreshParent', function(){
$state.reload(); //reload the state
})
}
function childCtr($scope){
// do something to update data and save in the same server.
someservice.update(data).then(function(){
//emit a message when success
$scope.$emit('refreshParent');
});
}
我试图在我更新他的子控制器中的数据后强制父控制器重新加载数据。 Html :
<div ng-controller='parentCtr'>
{{data}}
<mydirective></mydirective>
</div>
parentCtr 中的数据是通过这样调用服务从服务器获取的:
function parentCtr(){
$scope.data=someservice.getDate();
}
in mydirective: function childCtr(){
// do something to update data and save in the same server.
someservice.update(data);
}
我需要的是在 someservice.update() 成功后,我需要父级刷新数据并显示我的更新信息。
像这样调用服务
someService.update(data).then(function (response) {
recal funcation to load data
},
function (err) {})
尝试将函数传递到指令的范围。例如:
(function() {
'use strict';
angular
.module('myApp', []);
function myCtrl($scope){
$scope.controllerFn = function(){
console.log('Fired by directive');
};
}
function mydirective() {
return {
restrict: 'AE',
scope: {
parentFunction: '='
},
controller: function($scope, someservice) {
var data = {};
someservice
.update(data)
.then($scope.parentFunction, null);
}
};
}
angular
.module('myApp')
.controller('myCtrl', myCtrl)
.directive('mydirective', mydirective);
}());
<div ng-controller='myCtrl'>
<mydirective parent-function="controllerFn()"></mydirective>
</div>
你可以通过这种方式完成。调用成功发出消息,在父控制器中监听消息刷新状态或页面。
function parentCtr($scope,$state){
$scope.data=someservice.getDate();
$scope.$on('refreshParent', function(){
$state.reload(); //reload the state
})
}
function childCtr($scope){
// do something to update data and save in the same server.
someservice.update(data).then(function(){
//emit a message when success
$scope.$emit('refreshParent');
});
}