简体   繁体   中英

Two way databinding with a directive's controller in angular

Angular lets you setup two-way databinding with a directive's scope. Does anyone know of an easy way to setup two-way databinding with a directive's controller.

For example: http://plnkr.co/edit/TIxXrvYpP0na4xEeYLgS?p=preview

HTML

<body ng-app="myApp" ng-controller="MyCtrl as ctrl">
  Controller Test: {{ctrl.test}}
  <div dir test="ctrl.test"></div>
</body>

JS

var MyCtrl = function($timeout) {
  this.test = {msg: 'hello'};
  var _this = this;

  $timeout(function() {
    _this.test = {msg: 'good bye'};
  }, 1000);
}

angular.module('myApp', []).directive('dir', function() {
  return {
    scope: {
      test: '='
    },
    template: '\
      <div>Directive Scope Test: {{test}}</div>\
      <div>Directive Controller Test: {{dCtrl.test}}</div>',
    controller: function($scope) {
      this.test = $scope.test;
    },
    controllerAs: 'dCtrl'
  }
});

In the example above MyCtrl 's test variable is bound to the scope of the dir directive. But when the variable is assigned to the directive's controller ( this.test = $scope.test; ) the two-way binding is broken.

I'm assigning the scope variable to the controller just because I find it a bit awkward to go back and forth between using scope variables and controller variables when using the "controller as" syntax. However the best solution I can think of is to just access the variable directly off of $scope . Does anyone have a solution that fits better with "controller as" style controllers.

That is the only way in my opinion when you are working with angular 1.2.*, But in your specific case you are actually holding an old reference in the directive controller instance (since in your controller you are overwriting the reference held by test property completely by doing _this.test = {msg: 'good bye'}; ),while your directive controller instance is holding the old one (so changes are not reflected).

Instead if you do _this.test.msg = 'good bye'; you will see the change reflected since you are not overwriting the object reference in that case. Plnkr

There is no automatic way of attaching 2-way bound scope properties to the controller instance, unless you handle it via watches or using some syntactic sugar which will help you do it.

If you upgrade it to 1.3 rc you have a property bindToController:true which you can set so that properties will be automatically attached to the controller instance and not directly on the scope. Well ultimately the controller alias is attached to the scope though.

Plnkr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM