0

I have a directive that creates a button. When that button is clicked, it should update a variable firstName in the parent scope. I have already set $scope.firstName = "Test" in my controller.

The directive:

myApp.directive('myComponent', function(){
  return {
    scope: {
      firstName: '='
    },

    link: function(scope, element, attrs){
      // A function that should update a parent scope variable.
      scope.changeName = function(){
        scope.firstName = "Name was changed."
      }
    }),

    template: '<button ng-click="changeName">Test</button>'
  };

});

firstName should change here when the button is clicked, but it does not. Why does firstName not update?

<div>
  {{ firstName }}
  <my-component first-name="firstName"></my-component>
</div>
Don P
  • 60,113
  • 114
  • 300
  • 432
  • According to the [Directives angular documentation](https://docs.angularjs.org/guide/directive), you can only use {{firstName}} inside the directory template in order to share the same scope. Check the documentation part about "Isolating the Scope of a Directive" – Roberto Linares Feb 18 '15 at 02:24
  • I'm not sure I understand. Using `'='` creates a reference to the object in the parent scope. Since it's a reference, when I set firstName equal to something else, it should be changed. – Don P Feb 18 '15 at 02:29
  • @DonnyP check this for a possible solution: http://stackoverflow.com/questions/16845605/is-it-possible-to-update-parent-scope-from-angular-directive-with-scope-true – Augusto Barreto Feb 18 '15 at 02:40
  • 4
    One issue is that you aren't invoking `changeName` in your `ng-click` attr--you're just referencing it. You need the parens: `ng-click="changeName()"` – JAAulde Feb 18 '15 at 02:56
  • 2
    +1 to what @JAAulde said, you're not invoking `changeName`. Plunker for you. http://plnkr.co/edit/D3ad6Jkkjbl0ydAwHJj6?p=preview – miqh Feb 18 '15 at 02:58

1 Answers1

0

I think you missed out '()' on ng-click.

   myApp.directive('myComponent', function(){
       return {
          scope: { firstName: '=' },
          template: '<button ng-click="changeName()">Test</button>',
          link: function(scope, element, attrs){
               // A function that should update a parent scope variable.
                scope.changeName = function(){
             scope.firstName = "Name was changed."
          }
        }
      }
  });

Anyways, I have made a fiddle just to help you out. Check it and it is working fine. Revert me, if you have any other doubts. Link to fiddle:

http://jsfiddle.net/Satbir/84Letr9o/3/

Satbir Singh
  • 141
  • 2
  • 6