1

I'm trying to bind a variable inside a directive and modify it from the directive using the new Angular 1.4 bindToController syntax.

HTML:

<body ng-app="mainModule" ng-controller="mainController">
   <h2>{{boundVar}}</h2>
<my-directive ng-model="boundVar"></my-directive>

Javascript:

angular.module('directiveModule', []).directive('myDirective',
function()
{
    var r = 
    {
        scope: true,
        bindToController: { value: '=ngModel' },
        template: '<h2>The value is: {{ctrl.value}}</h2><br><button ng-click="ctrl.increment()">Increment</button>',
        controllerAs: 'ctrl',
        controller: function()
        {
            this.increment = function() { this.value++; };
        }
    };

    return r;
});

angular.module('mainModule', ['directiveModule']).controller('mainController',
function($scope)
{
    $scope.boundVar = 10;
});

When the page is initially load, you see the variable 'boundVar' as effectively been bound:

enter image description here

But when you press the button, only the inner variable changes, so the two-way binding appears not to work:

enter image description here

What am I missing?

Thank you!

user1275011
  • 1,552
  • 1
  • 16
  • 36
  • try bindToController : { boundVar: '=' }. You also arent using the correct syntax, in your case if you keep your original code the html should look like – ajmajmajma Jul 01 '15 at 17:34

1 Answers1

0

I believe this is just the common scenario that two-way binding will generally not work as expected if you are not using a '.' in your binding. You should not two-way bind to primitives. The same principle continues to apply, even with the new bindToController capabilities.

See https://stackoverflow.com/a/18128502/246811 for a better explanation.

Community
  • 1
  • 1
Phil Degenhardt
  • 7,215
  • 3
  • 35
  • 46