How do I get two way binding to work in Angular wi

2019-07-21 05:43发布

问题:

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 getter / setters in my controller. That is working sweet, but now I want to bind my directive's scope to my controller's scope two way, and it isn't working as I expect. I have created this codePen to show it.

http://codepen.io/anon/pen/DlfxB?editors=101

I expect this line to work:

scope: { pants: '='},

回答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',
        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(){},
          bindToController:true,
          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" src="https://code.angularjs.org/1.3.0-rc.1/angular.js"></script>

  <div ng-app="plunker">
    <div ng-controller="HelloEC5 as EC5">
      <p>HelloEC5 says my name is: {{EC5.fullName}} wearing {{EC5.pants}}!</p>
      <label>Pants:</label>
      <input ng-model="EC5.pants" type="text" />
      <label>FirstName:</label>
      <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" />
    </div>
  </div>