Misha Moroshko
Misha Moroshko

Reputation: 171351

AngularJS: How to set controller's property from a directive when using the "Controller As" syntax?

LIVE DEMO

Consider the following example that uses the Controller As syntax:

<body ng-app="myApp" ng-controller="MyCtrl as my">
  <div>
    {{ my.message }}
  </div>
  <button my-directive>
    Click me 
  </button>
</body> 
var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function() {
  this.message = 'Hello';
});

myApp.directive('myDirective', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        // Change 'message' here
      });
    }
  };
});

How could I set controller's message from the directive?

Without the "Controller As" syntax, I simply do: (DEMO)

scope.message = 'World';
scope.$apply();

But, how would you do this when using the "Controller As" syntax?

Upvotes: 1

Views: 1007

Answers (1)

Jesus Rodriguez
Jesus Rodriguez

Reputation: 12018

Since the controller is defined as my you need to use:

scope.my.message = 'World';
scope.$apply();

Upvotes: 4

Related Questions