w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I get two way binding to work in Angular with new controllerAs syntax and Object Oriented Controllers?

You can use bindToController option if you are in 1.3 rc version, to have the 2 way bound scope variables to be bound on the controller. Otherwise you would have to just manually map the properties to controller instance (Which is a pain) or just use regular syntax (without controller.) for 2 way bound properties. So you could do '<h1>{{my.pants}} - myDirective.pants = {{ my.pants }}</h1><input ng-model="my.pants">' with bindToController:true in the directive configuration.

  • When an isolate scope is used for a component (see above), and controllerAs is used, bindToController will
  • allow a component to have its properties bound to the controller, rather than to scope. When the controller
  • is instantiated, the initial values of the isolate scope bindings are already available.

   var myApp = angular.module('plunker', []);

    var helloEC5 = function(){
      this.pants = "jeans";
    helloEC5.prototype = {
        firstName: 'Seeya',
        lastName: 'Latir',
        get fullName() {
            return this.firstName + ' ' + this.lastName;
        set fullName (name) {
            var words = name.toString().split(' ');
            this.firstName = words[0] || '';
            this.lastName = words[1] || '';
    myApp.controller('HelloEC5', helloEC5);
    myApp.directive('myDirective', function () {
        return {
          scope: { pants: '='},
          controllerAs: 'my',
          controller: function(){},
          template: '<h1>{{my.pants}} - myDirective.pants = {{
my.pants }}</h1><input ng-model="my.pants">'
<script data-require="angular.js@1.3.0-rc.1" data-semver="1.3.0-rc.1"

  <div ng-app="plunker">
    <div ng-controller="HelloEC5 as EC5">
      <p>HelloEC5 says my name is: {{EC5.fullName}} wearing
      <input ng-model="EC5.pants" type="text" />
      <input ng-model="EC5.firstName" type="text" />
      <div my-directive="" pants="EC5.pants"></div>
      <hr />
      <label>Setting HelloEC5.fullName:</label>
      <input ng-model="EC5.fullName" />

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.