Gullfaxi171
Gullfaxi171

Reputation: 213

Can't access scope variable in directive (AngularJS)

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!

Upvotes: 0

Views: 1841

Answers (1)

jgawrych
jgawrych

Reputation: 3541

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.

Upvotes: 1

Related Questions