0

i have this html:

<button ng-click="reset()">
<div ng-controller="anotherController" class="container">
  <directive data="{{ datafordirective }}"></directive>
</div>

directive:

app.directive('directive', function(){
   return {
    restrict: 'AE',
    scope:{ data: '=', someAction: '=', reset: '='},
    link: function(scope, element, attrs){
     scope.reset = function(){
        //reset dataset
     };  
  }
};

});

I have inside my directive a function at the link function to reset the data but the problem is that the view where im using this button and this directive have a different controller but both directive and this view controller belong to the same app.module('appname', [])...

is there a way to achieve this? to use the scope.reset() function outside the directive scope?

Thanks!

Abdul Hamid
  • 168
  • 1
  • 7
  • 25
  • 1
    It will depend on if your directive creates an isolate scope. Can you show the JS code where you create the directive? – Ben Cook Nov 20 '15 at 14:44

1 Answers1

0

There are a number of ways you can do this. I'll give a couple of examples:

1. The Easy (and Non-Ideal) Way

Access the parent scope within the directive:

Instead of:

scope.reset = function() {};

use:

scope.$parent.reset = function() {};  

But modifying the parent scope from within a child scope is not a great practice. It can lead to confusion about the way scope inheritance works (What are the nuances of scope prototypal / prototypical inheritance in AngularJS?). Also, IMO, it is not great encapsulation.

2. A (Slightly) Better Way

<button ng-click="buttonClicked = true">
<div ng-controller="anotherController" class="container">
  <directive data="{{ datafordirective }}" reset="buttonClicked" reset-callback="buttonClicked = false"></directive>
</div>

Here we are using an attribute in the parent scope (buttonClicked) to control the directive through attributes on the element.

app.directive('directive', function(){
   return {
    restrict: 'AE',
    scope:{ data: '=', resetCallback: '&', reset: '='},
    link: function(scope, element, attrs){
     scope.$watch('reset', function(val) {
       if (val) {
         // reset dataset
         scope.resetCallback();
       }

     });
  }
};

The directive binds the value of buttonClicked to reset, then watches for that value to change, resetting the dataset when it does.

3. Another Better Way

Create a service to handle operations on your dataset.

app.service('dataset', function() {
  this.reset = function() {
    // reset dataset
  };
});

Then, somewhere in the parent controller, you need to inject the dataset service and create a function to call dataset.reset:

$scope.reset = function() {
  dataset.reset();
};
Community
  • 1
  • 1
Ben Cook
  • 1,654
  • 2
  • 18
  • 32
  • You might want to add `$on`, `$emit`, and `$broadcast` to that list. Part of the [AngularJS Scope API](https://docs.angularjs.org/api/ng/type/$rootScope.Scope) – georgeawg Nov 20 '15 at 18:43