Search code examples
javascriptangularjshtmlangularjs-directiveangular-directive

Data is not shown in created directive


My html looks like this:

<body ng-app="customDirective">
<div ng-controller="anController">
Date format: <input ng-model="fooData"> <hr/>
Current time is: <my-new-directive foo-Attr="{{fooData}}"></my-new-directive>
</div>
</body>
</html>

I would like to update data inside of my created tag my-new-directive if a scope property scope.fooData is changed.

So I have a scope property called fooData:

$scope.fooData = 'Hello World!:)';

and I am creating a directive:

(function(angular) {
  'use strict';
angular.module('customDirective', [])
  .controller('anController', ['$scope', function($scope) {
    $scope.fooData = 'Hello World!:)';
  }])
  .directive('myNewDirective', [function() {

    function link(scope, element, attrs) {
      var format,
          timeoutId;

      function updateValue() {
        element.text(format);
      }

      scope.$watch(scope.fooData, function(value) {
        format = value;
        updateValue();
      });
    }

    return {
      restrict: 'A',
      link: link,
      scope: {
         fooAttr: '@' 
      }
    };
  }]);
  document.createElement('my-new-directive');
})(window.angular);    

But if I write new values inside of input tag, then nothing occurs in my new directive.

Any help would be greatly appreciated! I am using AngularJS 1.5.8.


Solution

  • I see several mistakes and the directive is overly complex. On top of all comments above, this is wrong:

       return {
          restrict: 'A',
          link: link,
          scope: {
             fooAttr: '@' 
          }
        };
    

    You restrict the directive to act when added as an attribute. However in your example code:

    Current time is: <my-new-directive foo-Attr="{{fooData}}"></my-new-directive>
    

    You're using it as an element.

    Change your directive like this:

       return {
          restrict: 'AE', // allow it as element or attribute
          link: link,
          scope: {
             fooAttr: '@' 
          }
        };
    

    or

       return {
          restrict: 'E',  // only element
          link: link,
          scope: {
             fooAttr: '@' 
          }
        };
    

    also, remove this:

      document.createElement('my-new-directive');
    

    Check out this codepen: http://codepen.io/anon/pen/QdjBZr That should help you out.