【发布时间】:2015-11-15 12:26:09
【问题描述】:
我有一些父 Ctrl 实现了 locationChangeStart 函数。我也有子控制器,它将数据从 html 绑定到父控制器
html:
<div> <!-- parent ctrl setted in routing -->
<div ng-controller="ChildCtrl as childCtrl"
ng-init="childCtrl.setObjectName('somename')">
<textarea name="name" ng-model="parentObject.name"></textarea>
</div> <!-- end of child -->
</div> <!-- end of parent-->
父控件:
app.controller('ParentCtrl', function ($scope,$stateParams,config){
console.log("in parent");
$scope.timerPromise = null;
$scope.parentObject= {};
$scope.timerPromise = $interval(
function(){
},config.AUTOSAVE_TIMER_FREQUENCY);
console.log($scope.timerPromise);
$scope.$on('$locationChangeStart', function(event) {
if($scope.timerPromise) {
$interval.cancel($scope.timerPromise);
}
console.log("route changed in parent");
});
子控件
app.controller('ChildCtrl', function ($scope, $rootScope, $stateParams) {
console.log('in child');
var vm = this;
vm.objectId = $stateParams.id;
vm.setObjectName = function(objectName) {
console.log('setting object name in commets+'+objectName);
vm.objectName = objectName;
};
});
我的问题如下 - 从/到父 ctrl 变量的绑定没问题,我通过 ng-model 在子 ctrl 中看到来自服务器的数据,但在父 ctrl 中自动保存不起作用,因为 locationChangeStart 在加载父 ctrl 后触发 即使我没有按返回按钮,甚至没有按任何东西。位置更改事件停止计时器。 为什么即使我什么都没按,locationChangeStart 也会触发? 是因为嵌套控制器吗?我可以一起使用非别名、非 ng-controller 标记、在路由父控制器和别名子控制器中设置吗?
我的控制台输出如下:
in parent
Promise {$$state: Object, $$intervalId: 160} // timer promise
in child
setting object name in commets+somename
route changed in parent
你看,路线改变了,我的问题是关于那个奇怪的行为
【问题讨论】:
标签: angularjs angular-ui-router angular-controller