【发布时间】:2016-12-26 23:49:32
【问题描述】:
我有一个带有嵌套子控制器的主控制器
<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 所示。我阅读了this article onswitching to prototype继承样式的范围,但我不确定这是解决我的问题的最佳方法,因为我不确定我是否走在正确的道路上。也许我应该使用事件发射器/广播器来实现我想要的效果?
如何更新searchController 的父范围(mainController) 中的results 变量,以便searchController 的兄弟姐妹可以访问它?
编辑/解决所以,这真的很奇怪,如果你能解释为什么会这样,金星给你。
这是代码不起作用工作时的主控制器:
.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);
}]);
这是代码起作用时的主控制器:
.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);
}]);
为什么...
【问题讨论】:
标签: javascript angularjs angularjs-scope angularjs-watch