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