Is there a way to watch when one property in an object changes? I tried
var unwatch = obj.$watch(function() {
console.log("data changed");
});
That fired when any property in the object changes. I tried
var unwatch = obj.myProperty.$watch(function() {
console.log("data changed");
});
That returned an error message: "TypeError: obj.myProperty.$watch is not a function".
I tried
var myTargetValue = $firebaseObject(ref.myProperty);
That returned an error message: "TypeError: Cannot read property 'ref' of undefined".
You'll have to create a $firebaseObject
for the property. But, using the Firebase SDK tends to be more useful than $watch()
.
angular.module('app', ['firebase'])
.constant('FirebaseUrl', 'https://34474165.firebaseio-demo.com/')
.service('rootRef', ['FirebaseUrl', Firebase])
.controller('MyCtrl', MyController);
function MyController($scope, $firebaseObject, rootRef) {
var objRef = rootRef.child('obj');
var obj = $firebaseObject(objRef);
var objMessage = $firebaseObject(rootRef.child('obj/message'));
// watch the whole object
var unwatch = obj.$watch(function(a) {
console.log(a);
});
// watch a child property
objMessage.$watch(function(a) {
console.log(a, 'msg');
});
// get the whole object as it changes
objRef.on('value', function(snap) {
console.log(snap.val());
});
// get the child property as it changes
objRef.child('message').on('value', function(snap) {
console.log(snap.val());
});
}