Search code examples
angularjsangularjs-ng-transclude

AngularJS - directive with ng-transclude, no two-way binding


See that DEMO

<body ng-controller="MainCtrl">

    {{ obj }}

    <dir>
      <input type="text" ng-model="obj" />
    </dir>

  </body>

Why when I change the obj scope variable in the custom directive with ng-transclude I don't change it in the MainCtrl $scope.obj.

But when I have $scope.obj = { name : 'test' }; in MainCtrl the two-way binding is working the way I expect.

See the working DEMO

<body ng-controller="MainCtrl">

    {{ obj.name }}

    <dir>
      <input type="text" ng-model="obj.name" />
    </dir>

  </body>

What is the explanation of this behavior?


Solution

  • There is an issue with accessing primitive variables on the parent scope from the child scope. You have a child scope because having transclude: true creates a new scope.

    You really should read this article to have a deep understanding of what's going on.

    The highlights from the article:

    Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope.

    And

    This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models.

    What happens is that the parent scope is not consulted when it comes to primitives. It's a Javascript thing, not even Angular's.

    I've also created a Demo of object hiding from child scope. (shadowing a non-primitive object):

    app.directive('dir', function () {
        return {
            restrict: 'E',
    
            scope: true,
            template: "<div><input type=\"text\" ng-model=\"obj.name\" /></div>",
            link: function(scope, element, attrs) {
              scope.obj = {name : "newname"}; 
            }
    
        };
    });