0

What I'd like to do is very simple: two way bind a directive's scope. This means given a Parent controller ParentCtrl with $scope.name='Foo' and a directive with scope: {name: '='} I'd expect that when I change scope.name='Bar' from within the directive's link function or $scope.name='Bar' from the given directive's controller I would expect that the the template for ParentCtrl would reflect the new $scope.name, otherwise it's only one way bound from the parent scope to the directive's scope. Unfortunately that is not what I am getting. Am I missing something here? Here's a plunker link illustrating the issue:

http://plnkr.co/edit/VeGvWV2AGftFHF0LhnBY?p=preview

the code:

angular.module('docsSimpleDirective', [])
  .controller('ParentCtrl', ['$scope', function($scope) {
    $scope.name = "Bernie Sanders";
    $scope.occupation = "Arsonist";
  }])
  .directive('myCustomer', function() {
    return {
      template: 'Name: {{name}} Occupation: {{occupation}}',
      scope: {
        name: '=',
        occupation: '='
      },
      link: function(scope, element, attrs) {
        scope.name = "Donald Drumpf";
        scope.occupation = "Fascist pig";
        scope.$apply();
      }
    };
  });

the Template:

<body ng-app="docsSimpleDirective" ng-controller="ParentCtrl">
  Name: {{name}}, Occupation: {{occupation}}<br />  

  <div ng-controller="ParentCtrl">
    <div my-customer name="name" occupation="occupation"></div>
  </div>
</body>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
micahblu
  • 4,924
  • 5
  • 27
  • 33
  • You've created an isolated scope in your directive, why do you expect changes to be propagated upwards? – user3707125 Mar 17 '16 at 22:14
  • Because two way binding is extremely useful. What I'm really asking here is; is two way binding possible with directives? – micahblu Mar 17 '16 at 22:16
  • 1
    Oh, I think I get your mistake - take a look at this answer: http://stackoverflow.com/a/23699009/3707125 and this one: http://stackoverflow.com/a/29265539/3707125 – user3707125 Mar 17 '16 at 22:19

1 Answers1

3

The problem is you had multiple instances of ParentCtrl, 1st one is on body and then there it is on one of inner div.

So when you are declaring name on a scope variable, you are declaring it as a primitive type, so overriding value inside inner controller will simple have new reference for $scope.name value. Prototypal inheritance will only follow in case of objects not on primitive type variable.

You should do follow dot rule while defining ng-model's on page.

Also no need to run digest cycle inside directive link function. That will end up throwing error. Please remove that from there.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299