Organizational Research By

Surprising Reserch Topic

watching for data changes in an angular directive

watching for data changes in an angular directive  using -'javascript,angularjs,angularjs-directive'

How can I trigger a $watch variable in an Angular directive when manipulating the data inside (e.g., inserting or removing data), but not assign a new object to that variable?

I have a simple dataset currently being loaded from a JSON file.  My Angular controller does this, as well as define a few functions:

App.controller('AppCtrl', function AppCtrl($scope, JsonService) {
    // load the initial data model
    if (!$ {
        JsonService.getData(function(data) {
            $ = data;
            $scope.records = data.children.length;
    } else {
        console.log("I have data already... " + $;

    // adds a resource to the 'data' object
    $scope.add = function() {
        ${ "name": "!Insert This!" });

    // removes the resource from the 'data' object
    $scope.remove = function(resource) {
        console.log("I'm going to remove this!");

    $scope.highlight = function() {


I have a <button> that properly called the $scope.add function, and the new object is properly inserted into the $ set.  A table I have set up does update each time I hit the "add" button.

<table class="table table-striped table-condensed">
    <tr ng-repeat="child in data.children | filter:search | orderBy:'name'">
      <td><input type="checkbox"></td>
      <td><button class="btn btn-small" ng-click="remove(child)" ng-mouseover="highlight()"><i class="icon-remove-sign"></i> remove</button></td>

However, a directive I set set up to watch $ is not being fired when all this happens.

I define my tag in HTML:

<d3-visualization val="data"></d3-visualization>

Which is associated with the following directive (trimmed for question sanity):

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 get the "I see a data change!" message at the very beginning, but never after as I hit the "add" button.

How can I trigger the $watch event when I'm just adding/removing objects from the data object, not getting a whole new dataset to assign to the data object?
asked Oct 7, 2015 by deepak gupta
0 votes

Related Hot Questions

Government Jobs Opening