Is there a way to activate a $watch variable in an Angular directive when modifying the data within it (eg. adding or removing data), without assigning a completely new object to that variable?
Currently, I am loading a basic dataset from a JSON file using my Angular controller, which also contains a few functions:
App.controller('AppCtrl', function AppCtrl($scope, JsonService) {
// Load the initial data model
if (!$scope.data) {
JsonService.getData(function(data) {
$scope.data = data;
$scope.records = data.children.length;
});
} else {
console.log("I already have the data... " + $scope.data);
}
// Adds a resource to the 'data' object
$scope.add = function() {
$scope.data.children.push({ "name": "!Insert This!" });
};
// Removes a resource from the 'data' object
$scope.remove = function(resource) {
console.log("I'm going to remove this!");
console.log(resource);
};
$scope.highlight = function() {
};
});
I have a <button>
that correctly calls the $scope.add
function, and the new object is properly added to the $scope.data
set. The table I have updates each time the "add" button is clicked.
<table class="table table-striped table-condensed">
<tbody>
<tr ng-repeat="child in data.children | filter:search | orderBy:'name'">
<td><input type="checkbox"></td>
<td>{{child.name}}</td>
<td><button class="btn btn-small" ng-click="remove(child)" ng-mouseover="highlight()"><i class="icon-remove-sign"></i> remove</button></td>
</tr>
</tbody>
</table>
However, the directive I created to watch $scope.data
does not trigger when these actions occur.
In HTML, I define my tag as:
<d3-visualization val="data"></d3-visualization>
This tag is associated with the following directive (trimmed for simplicity):
App.directive('d3Visualization', function() {
return {
restrict: 'E',
scope: {
val: '='
},
link: function(scope, element, attrs) {
scope.$watch('val', function(newValue, oldValue) {
if (newValue)
console.log("I see a data change!");
});
}
}
});
I receive the message "I see a data change!" at the beginning, but not after clicking the "add" button.
How can I trigger the $watch event when simply adding/removing objects from the data object, rather than receiving a whole new dataset to assign to the data object?