0

I want to make a directive that behaves like a container by transcluding its contents. My html looks like this

<test>
    <input type="text" ng-model="name" />
    <button ng-click="alertName()">Alert</button>
</test>

Controller and directive are like this

angular.module('app', [])
  .controller('TestCtrl', function($scope) {
    $scope.name = 'Eric Cartman';

    $scope.alertName = function() {
      alert($scope.name);
    };
  })
  .directive('test', function() {
    return {
      restrict: 'E',
      template: '<div ng-transclude></div>',
      transclude: true,
      replace: true,
      link: function($scope, elem, attr, ctrl) {

      }
    };
  });

When the page loads I see 'Eric Cartman' in the textbox and when I click 'Alert' button I see 'Eric Cartman' in the dialog box. Till here everything is fine.

The problem is when I change the name in the textbox and hit the 'Alert' button it still alerts 'Eric Cartman'. Where am I going wrong?

Here is the Plunker

1 Answer 1

2

This is due to the prototypical inheritance of the scopes and the bound variable being "top level" (i.e. ng-model="name", instead of ng-model="model.name").

Just wrap the value in an object:

// controller:
$scope.model = { name: 'Eric Cartman' };
// do not forget the alert!

Of course bind it properly:

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

The prototypical inheritance is a topic that confuses people when first exposed to it; I haven't even tried to explain the concept here, there are plenty of sources in the web. You may study it or just take my word for it and never use "top-level" 2-way bindings!

Sign up to request clarification or add additional context in comments.

1 Comment

Was just in the middle of answering this, here's the plunkr showing @Nikos explanation plnkr.co/edit/d0BQDUUJm6x1crXlAYB0?p=preview

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.