Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoid referencing parent scope in angularjs directive
    primarykey
    data
    text
    <p>I am writing a directive to display data from server in an HTML table called <code>djlist</code></p> <pre><code>directive('djlist', function(urls) { return { restrict: 'ACE', templateUrl: urls.list_objs_template, scope: {}, controller: ['$scope', '$resource', function($scope, $resource) { $scope.objs = $resource(urls.list_objs); $scope.objs_api = $resource(urls.list_objs_api); $scope.data = $scope.objs.get(); } ] }; }) </code></pre> <p>The data from server are displayed with <code>ng-repeat</code>. Each object in the data array has a delete button attached to it, which is another directive called <code>djdel</code></p> <pre><code>&lt;div class="row panel panel-primary"&gt; &lt;h3 class="panel-heading"&gt;Data from REST&lt;/h3&gt; &lt;div class="panel-body"&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;th&gt;Content&lt;/th&gt; &lt;th&gt;Date Created&lt;/th&gt; &lt;th&gt;Action&lt;/th&gt; &lt;/tr&gt; &lt;tr ng-repeat="d in data.objects"&gt; &lt;td&gt;{{ d.content }}&lt;/td&gt; &lt;td&gt;{{ d.date }}&lt;/td&gt; &lt;td&gt; &lt;djdel ng-click="del($index)" model-pk="d.id"&gt;&lt;/djdel&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Here is how I define <code>djdel</code></p> <pre><code>directive('djdel', function() { return { restrict: 'ACE', template: '&lt;button class="btn btn-danger btn-small"&gt;Delete&lt;/button&gt;', scope: { modelPk: '=' }, controller: ['$scope', '$http', '$resource', function($scope, $http, $resource) { $scope.del = function(index) { var $parent = $scope.$parent.$parent; $parent.objs_api. remove({id: $scope.modelPk}, function() { $parent.data.objects.splice(index, 1); }); }; } ] }; }). </code></pre> <p>This works. However, after my object is successfully deleted from the server, which is initiated in the <code>djdel scope</code>, I need a way to refresh the data collection, which is in the <code>djlist scope</code>. The scope hierarchy is <code>djlist &gt; ng-repeat &gt; djdel</code>, hence <code>$scope.$parent.$parent</code> when referencing data collection. </p> <p>Is there any way to avoid referencing so many levels up the scope chain?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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