user_909
user_909

Reputation: 57

Change Controller variable value from change in isolate scope directive

So I know with two way binding, =, in a directive a controller's value can be passed into the directive. But how do you pass a change in the isolated directive back to the controller?

So for example, I have a form that has a slider built with a directive with an isolated scope. Initial value is set from controller, then changes in directive with isolate scope.

What I'm trying to do is change the controller's value when the directive variable with two way binding changes as well.

Any suggestions?

Upvotes: 1

Views: 4895

Answers (2)

bluenavajo
bluenavajo

Reputation: 483

You have two possible ways of achieving this. One is creating a watch statement in the controller on the variable that you passed into the directives isolate scope.

// code in view controller
$scope.sliderValue = 0;
$scope.$watch('sliderValue', function(newValue) {
  if (angular.isDefined(newValue)) {
    // Do stuff with new slider value
  }
});

Note that we need the isDefined, because every watch fires on scope compilation with the initial value being undefined.

The other way is enhancing your directive with a parameter which is evaluated as your slider value changes (much like a callback function).

// sample directive code
angular.module('my-ui-controles', []).directive('mySlider', [function() {
  return {
    template: '...',
    scope: {
      value: '=mySlider',
      onChange: '&'
    },
    link: function(scope, elem, attrs) {
      // assume this is called when the slider value changes
      scope.changeValue = function(newValue) {
        // do other internal stuff and notify the outside world
        scope.onChange({value: newValue});
      }
    }
  }
}])

And now you can use this in the template likes this:

<div my-slider="sliderValue" on-change="doStuff(value)"></div>

What happens now is as soon as the slider value changes we evaluate the onChange expression that is passed into the directive. The value in doStuff is filled with your new slider value. The object that we have passed on to onChange actually is the scope with which the expression is evaluated and doStuff can be any method from your controller.

The main benefit is that you have the logic for notifying somebody in your directive rather than implicitly in your controller through a watch.

Hope that gets you in the right direction.

Upvotes: 5

Hazarapet Tunanyan
Hazarapet Tunanyan

Reputation: 2865

If you have pass any variable to isolated scope you can bind it (set any listener on it) in both sides.You can event use Angularjs Events to send any signal, if variable as been changed.

maybe this articles can help you.

http://www.w3docs.com/snippets/angularjs/bind-variable-inside-angularjs-directive-isolated-scope.html

http://www.w3docs.com/snippets/angularjs/change-variable-from-outside-of-directive.html

Upvotes: 1

Related Questions