1

I'm using the "Controller as" syntax and am in a situation where I'd like the Directive to communicate with the Controller.

I can get this to work when I do NOT use the "Controller as" syntax. Plunkr links below for both working and non-working versions.

Also - I'm curious to hear if the approach is in line with the "angular way".

Does NOT work:

<body ng-controller="MainCtrl as main">
  <div char-count>I like characters, they fill content with stuffs.</div>
  <p>{{main.chars}} characters inside the char-count directive!</p>
</body>

and...

app.controller('MainCtrl', ['$scope', '$window', 
  function($scope) {
    this.name = 'World';
    this.chars = 0;
    this.setCharCount = function(elem) {
      this.chars = elem[0].innerHTML.length - 1;
    }
  }
]);

app.directive('charCount', ['$window',
  function($window) {
    return {
      link: function(scope, elem, attrs) {
        scope.name = "this setting of scope works!";
        scope.setCharCount(elem);
        elem.css("width", scope.chars + "px");
      }
    }
  }
]);

Plunkr Working Version: http://plnkr.co/edit/9JaQDwxDmE9uDqq7v0Xv?p=preview

Plunkr Non-workign version with "Controller as" syntax: http://plnkr.co/edit/dIoq9r66mOhuMSQK7woj?p=preview

1 Answer 1

1

In your "controller as" version, you are assigning the methods and properties to this (the controller), which is made available on the scope under the "as" name you gave it (in this case, you're using "MainCtrl as main" so it the controller would be accessible as scope.main). The working version of your "controller as" directive looks like this:

app.directive('charCount', ['$window',
  function($window) {
    return {
      link: function(scope, elem, attrs) {
        scope.main.name = "this setting of scope works!";
        scope.main.setCharCount(elem);
        elem.css("width", scope.main.chars + "px");
      }
    }
  }
]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Problematic. Worked and makes sense; feel a bit silly. New to Angular and bouncing around what makes sense to go in Directive and what in Controller (without a service) according to Angular's recommended methodology.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.