Skip to content Skip to sidebar Skip to footer

How Do I Get Two Way Binding To Work In Angular With New Controlleras Syntax And Object Oriented Controllers?

I am fearful of 'scope soup', people hanging too much functionality off the $scope. So I am experimenting with OO oriented controllers, the new controllerAs and using EC5 style get

Solution 1:

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.

bindToController
  • 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.

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

    var helloEC5 = function(){
      this.pants = "jeans";
    };
    helloEC5.prototype = {
        firstName: 'Seeya',
        lastName: 'Latir',
        getfullName() {
            returnthis.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(){},
          bindToController:true,
          template: '<h1>{{my.pants}} - myDirective.pants = {{ my.pants }}</h1><input ng-model="my.pants">'
        }
    });
 })();
<scriptdata-require="angular.js@1.3.0-rc.1"data-semver="1.3.0-rc.1"src="https://code.angularjs.org/1.3.0-rc.1/angular.js"></script><divng-app="plunker"><divng-controller="HelloEC5 as EC5"><p>HelloEC5 says my name is: {{EC5.fullName}} wearing {{EC5.pants}}!</p><label>Pants:</label><inputng-model="EC5.pants"type="text" /><label>FirstName:</label><inputng-model="EC5.firstName"type="text" /><divmy-directive=""pants="EC5.pants"></div><hr /><label>Setting HelloEC5.fullName:</label><inputng-model="EC5.fullName" /></div></div>

Post a Comment for "How Do I Get Two Way Binding To Work In Angular With New Controlleras Syntax And Object Oriented Controllers?"