我有一个带有嵌套子控制器的主控制器
<div class='main' ng-controller='mainController'>
<div class='search' ng-controller='searchController'>
<input type='text' ng-model='keyword'>
<button ng-click='search(keyword)'>Search!</button
</div>
</div>
在我的主控制器中,我尝试创建一个主范围变量来存储搜索结果。
var app = angular.module('mapApp', [])
.controller('mainController', [
'$scope',
'$searchFactory',
($scope, searchFactory)=>{
$scope.results = [];
$scope.$watchCollection('results', (newVal, oldVal)=>{
console.log('results updated to, ', newVal);
}, true);
}]);
然后我尝试$scope.results
在我的子控制器中更新主控制器的变量。
app.controller('searchController', ['$scope', 'searchFactory', ($scope, searchFactory)=>{
$scope.search = function(keyword, type){
let request = {
location: $scope.location,
radius: '500',
type: type ? type : undefined,
keyword: keyword
};
searchFactory.search(request, (result)=>{
console.log('result from search was', result);
$scope.results = result;
});
};
}]);
我的$watch
函数没有被调用,我相信这是因为$scope.results
没有被更新。我尝试过使用这三种类型的$watch
函数,如$scope.watch depths部分下的Angular Docs所示。我阅读了这篇关于为范围切换到原型继承样式的文章,但我不确定这是解决我的问题的最佳方法,因为我不确定我是否走在正确的道路上。也许我应该使用事件发射器/广播器来实现我想要的效果?
如何更新的父范围 ( )results
中的变量,以便我可以让 的兄弟姐妹访问它?searchController
mainController
searchController
编辑/解决所以,这真的很奇怪,如果你能解释为什么会这样,金星给你。
这是代码不起作用时的 mainController :
.controller('mainController', [
'$scope',
'searchFactory',
($scope,searchFactory)=>{
$scope.searchData = {results:[]};
$scope.setResults = function(newResults){
$scope.searchData.results = newResults;
console.log('new results is', $scope.searchData.results);
};
//this function doesn't invoke except on initiation
$scope.$watch('searchData.results', (newVal, oldVal)=>{
console.log('results updated to, ', newVal);
}, true);
}]);
这是代码正常工作时的mainController:
.controller('mainController', [
'$scope',
'searchFactory',
($scope,searchFactory)=>{
$scope.searchData = {results:[]};
//comment out the evil console log and... it works??!!
$scope.setResults = function(newResults){
$scope.searchData.results = newResults;
//console.log('new results is', $scope.searchData.results);
};
//this invokes now, because black magic?
$scope.$watch('searchData.results', (newVal, oldVal)=>{
console.log('results updated to, ', newVal);
}, true);
}]);
为什么...