私は私のメインコントローラには、ネストされた子コントローラparentScope配列がchildScopeの角度を変更したときに、それをどのように更新できますか?
<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
が更新されていないためであると考えている、呼び出されません。私はAngular Docsの$ scope.watchの深さセクションに示すように、3種類の$watch
関数を使用しようとしました。私はthis articleをスコープ用のプロトタイプ継承スタイルに切り替えることを読んでいますが、正しいパスを辿るかどうかわからないため、私の問題を解決する最良の方法であるとは確信していません。おそらく、私は希望の効果を達成するためにイベントエミッタ/放送局を代わりに使用する必要がありますか?私はその後、searchController
の兄弟によって、それがアクセス可能持つことができるように
にはどうすればsearchController
の親スコープ(mainController
)でresults
変数を更新することができますか?
EDIT /だから、を解決し、これは本当に奇妙あり、これはあなたのためのケース、金の星であるなぜあなたは説明することができます。ここで
コードが動作しない場合メインコントローラである:
.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);
}]);
なぜ...
:.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);
}]);
ここでは、メインコントローラは、コードが作業を行うときであります
を、それはまだありませんいくつかの理由についてワーキング。結果を適切に設定していますか? 'searchController'では、' $ scope.searchData.results = result'を実行します。ここで 'result'はhttpリクエストから返される配列です –
時計機能には何か問題があるかもしれないと感じています関数はsetter関数を使用していても呼び出されません: '$ scope.setResults = function(newResults){ $ scope.results = newResults; console.log( '新しい結果は'、$ scope.results); }; ' –
さて、セッターであっても、$ watch関数は呼び出されません。正確な構文は次のとおりです: '$ scope。$ watchCollection( 'searchData。結果 '、(newVal、oldVal)=> { console.log(' results to updated '、newVal); }、true); ' –