Note that there are some explanatory texts on larger screens.

plurals
  1. PO$watch'ing for data changes in an Angular directive
    text
    copied!<p>How can I trigger a <code>$watch</code> 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?</p> <p>I have a simple dataset currently being loaded from a JSON file. My Angular controller does this, as well as define a few functions:</p> <pre><code>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 have data already... " + $scope.data); } // adds a resource to the 'data' object $scope.add = function() { $scope.data.children.push({ "name": "!Insert This!" }); }; // removes the resource from the 'data' object $scope.remove = function(resource) { console.log("I'm going to remove this!"); console.log(resource); }; $scope.highlight = function() { }; }); </code></pre> <p>I have a <code>&lt;button&gt;</code> that properly called the <code>$scope.add</code> function, and the new object is properly inserted into the <code>$scope.data</code> set. A table I have set up does update each time I hit the "add" button.</p> <pre><code>&lt;table class="table table-striped table-condensed"&gt; &lt;tbody&gt; &lt;tr ng-repeat="child in data.children | filter:search | orderBy:'name'"&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;{{child.name}}&lt;/td&gt; &lt;td&gt;&lt;button class="btn btn-small" ng-click="remove(child)" ng-mouseover="highlight()"&gt;&lt;i class="icon-remove-sign"&gt;&lt;/i&gt; remove&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>However, a directive I set set up to watch <code>$scope.data</code> is not being fired when all this happens.</p> <p>I define my tag in HTML:</p> <pre><code>&lt;d3-visualization val="data"&gt;&lt;/d3-visualization&gt; </code></pre> <p>Which is associated with the following directive (trimmed for question sanity):</p> <pre><code>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!"); }); } } }); </code></pre> <p>I get the <code>"I see a data change!"</code> message at the very beginning, but never after as I hit the "add" button.</p> <p>How can I trigger the <code>$watch</code> event when I'm just adding/removing objects from the <code>data</code> object, not getting a whole new dataset to assign to the <code>data</code> object?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload