数据未显示在创建的指令中

Data is not shown in created directive

我的 html 看起来像这样:

<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>

如果范围 属性 scope.fooData 发生变化,我想更新我创建的标签 my-new-directive 内的数据。

所以我有一个范围 属性 叫做 fooData:

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

我正在创建一个指令:

(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);    

但是如果我在输入标签中写入新值,那么我的新指令中什么也不会发生。

如有任何帮助,我们将不胜感激!我正在使用 AngularJS 1.5.8.

几个错误

  1. 指令名称应为 cammelCase
  2. 属性应该foo-attr而不是fooAttr
  3. 因为你有 @(单向绑定)你应该使用 foo-attr="{{fooData}}"

改变

<div ng-anController="anController">

<div ng-controller="anController">

并尝试遵循更好的命名约定,例如 app 名称不应具有 directive 后缀,并且 directive 名称也应在 camelcase 中,如@pankajParkar 所述.

  1. ng-anController="anController",好像应该是ng-controller="anController".

  2. 你应该看 scope.fooAttr 而不是 scope.fooData

我看到几个错误,指令过于复杂。 在以上所有评论之上,这是错误的:

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

您限制指令在添加为属性时起作用。 但是在您的示例代码中:

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

您正在将其用作元素。

像这样更改您的指令:

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

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

另外,删除这个:

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

查看此代码笔:http://codepen.io/anon/pen/QdjBZr 那应该能帮到你。