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

3
  • ng-transclude 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"). Commented May 29, 2014 at 4:57
  • thanks, it turns out (as I found at the related question just now stackoverflow.com/questions/14481610/…) 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 Commented May 29, 2014 at 5:03
  • I found this short video to be pretty helpful. I still forget sometimes even with this knowledge somewhere in the back of my mind. Commented May 29, 2014 at 5:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.