SL Dev SL Dev - 1 month ago 17
AngularJS Question

Exposing AngularJS directive property value to parent controller

I am working on an AngularJS app. I am trying to write a reusable component to use throughout my app. For the sake of demonstration, we'll just use a text box. I've created a fiddle of my attempt here. Basically, I'm trying to use a control like this:

<div ng-app="myApp">
<div ng-controller="myController">
<my-control textValue="{{controlValue}}"></my-control>
<br />
You entered: {{controlValue}}
</div>
</div>


Unfortunately, I cannot figure out how to bind a property between the scope of the controller and the scope of the directive. I'm not sure what I'm doing wrong in my fiddle. Can someone please tell me what I'm doing wrong?

Thank you!

Answer

You were not so far, but you need to be carefull when using {{}}

Remove braces and don't use camelNotation for text-value attribute :

<div ng-app="myApp">
  <div ng-controller="myController">
      <my-control text-value="controlValue"></my-control>
      <br />
      You entered: {{controlValue}}
  </div>
</div>

Use ng-model attribute :

angular.module('ui.directives', []).directive('myControl',
  function() {
    return {
      restrict: 'EAC',

      scope: {
          textValue: '='
      },
        template: '<input type="text" ng-model="textValue"></input>'
    };
  }
);