0

Why doesn't the two way binding work in the following directive?

Module:

angular.module('main')
.controller('MainController', ['$scope', 'TestService', function ($scope, TestService) {
    $scope.name = "Aaron";

    $scope.data = "Initial";

    $scope.dataClicked = function () {
        alert($scope.data);
    };
}]);

Directive:

var angularStartDirectives = angular.module('angularStart.directives', []);    
angularStartDirectives.directive('outputText', function () {
    return {
        transclude: true,
        template: '<div ng-transclude></div>'
    };
});

Form:

<form>
    <div data-output-text>
        <p>Hello {{name}}</p>
        <input type="text" ng-model="data" />
    </div>
    <div>{{data}}</div>
    <button type="button" ng-click="dataClicked()">Go</button>
</form>

The result is that the transcluded content receives the value of $scope.data initially but updates to the bound input do not propagate up to the parent scope.

Initial load

Upon updating the bound text box

Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121
  • [`ng-transclude`](https://github.com/angular/angular.js/wiki/Understanding-Scopes) creates a new scope. If you prefix your `ng-model` with `$parent` it should work as you expect - though it may not be an elegant solution for your case (i.e. `ng-model="$parent.data"`). – miqh May 29 '14 at 04:57
  • thanks, it turns out (as I found at the related question just now http://stackoverflow.com/questions/14481610/angularjs-two-way-binding-not-working-in-directive-with-transcluded-scope?rq=1) that if you bind to an object property in the scope, it "just works" - obviously I need to dive deeper to understand why... but I do believe I have a solution... thanks for your comment too – Aaron Anodide May 29 '14 at 05:03
  • I found [this short video](https://www.youtube.com/watch?v=DTx23w4z6Kc) to be pretty helpful. I still forget sometimes even with this knowledge somewhere in the back of my mind. – Marc Kline May 29 '14 at 05:16

0 Answers0