0

I would like to change update a directive each time a value is updated into a controller.

Unfortunately I don't manage to access the scope value from the directive.

Here's the code of the directive :

myApp.directive( 'raphael', function ($compile, $document, $timeout) {
  return {
    link: function ( scope, element, attrs ) {


    var paper = new Raphael(element[0], 600, 600);
// I need it right here !

I've tried with $ watch:

scope: {variable: '='},
link: function ( scope, element, attrs ) {
  scope.$watch(variable, function(){
    console.log(variable);

but it's not working

Then, how could I do to "update" the whole directive each time the variable is updated in the controller?

thanks!

1 Answer 1

1

You have just a simple problem with your $watch that's somewhat difficult to explain. "variable" is not a defined variable in the code's scope (not the variable called scope from angular, but the actually scope of the JavaScript function) of the linking function.

Perhaps code could explain it better than words:

scope: {variable: '='},
link: function ( scope, element, attrs ) {
  scope.$watch("variable", function (variable) {
    console.log(variable);

Let's rename variable to something more definitive to show what's going on. For the variable that resides on the scope, we'll call 'foo' and the value of foo passed in by $watch we will call 'bar'

scope: {foo: '='},
link: function ( scope, element, attrs ) {
  scope.$watch("foo", function (bar) {
    console.log(bar);

Thus $scope.foo is a variable that resides on $scope, which is two-way bound by your element's foo attribute. bar is the newValue that the $watch function passes back.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer ! It works ! (I also did not understand I had to write into html : <div foo = "somedata">)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.