私は$scope
フィールドの概要を総称して関数make_value_summary
を持っています。ここではlocation_summary
を構築するためにそれを使用しており、ビューにはng-bind
を介してバインドされています。フィールドstreet
,suburb
、またはstate
が更新されるたびにlocation_summary
が更新されます。
$scope.location_summary = function() {
var fields = [
'street',
'suburb',
'state',
];
return make_value_summary(fields, $scope, 'Location?');
};
function make_value_summary(fields, $scope, initial) {
var summary = '';
fields.forEach(function(field) {
if ($scope[field] && $scope[field] !== '0') {
if (summary) {
summary = summary + ', ' + $scope[field];
}
else {
summary = $scope[field];
}
}
});
if (summary) {
return summary[0].toUpperCase() + summary.substring(1);
}
else {
return initial;
}
}
質問1:location_summary
が最初に割り当てられているとき、どのようlocation_summary
が動的に更新さん、それはmake_value_summary
のようなコードでの私の最初の表情からは、一度だけ実行する必要があります。
質問2:location_summary
をサービスを通じてビューの全く異なる部分にバインドしたいとします。サービスLocation
にlocation_summary
をつけてどうすればいいですか?私は$watch
を使ってみましたが、成功しませんでした。
$scope.$watch('location_summary', function(newValue, oldValue) {
// Just gives unevaluated reference to location_summary function
console.log(newValue);
console.log(oldValue);
});
EDITは、時計の '評価する' 機能、すなわち$watch()
に'location_summary()'
に渡すことによって2へ溶液を得ました。まだ私の最初の質問への答えが欲しいです!