用指令看不到模板的内容

时间:2015-02-02 17:13:03

标签: angularjs html5 angularjs-directive

我的指令存在问题,该指令不添加模板元素。 该指令包含在.html文件中。 控制台不显示任何错误。

directive.js:

app.directive('myDirective', function() {
  return {
    restrict: 'A',
    require: '^ngModel',
    scope: {
        ngModel: '='
    },
    template: '<span>see this ? {{ ngModel }}</span>'
  }
});

HTML:

<div my-directive ng-model="content"></div>

我不知道为什么会发生这种情况

2 个答案:

答案 0 :(得分:1)

这是因为您使用的是:&#39; ^ ngModel&#39;

这不符合你的想法。

require在嵌套指令时使用,或者需要从另一个指令访问控制器。例如,如果你是从一个项目列表中创建一个手风琴,你可以得到一个名为“手风琴包裹”的指令。在包装整个列表的元素上,然后在每个元素上指定一个名为&#39; accordian-item&#39;。

那么,你会有类似的东西......

app.directive('accordianWrap', function() {
  return {
   restrict: 'A',
   template: 'template.html',
   controller: [function() {
   }]
  }
});

app.directive('accordianItem', function() {
  return {
   restrict: 'A',
   require: '^accordianWrap',
   template: 'template.html'
  }
});

编辑:我错误地使用了需要打破它,它仍然可以使用require但是在你使用它的情况下,它没有做任何事情。

编辑:Plunker是愚蠢的,所以这里有一个工作的jsfiddle,也将内容传递给指令。

http://jsfiddle.net/bhofuxeo/

答案 1 :(得分:0)

您添加的require: '^ngModel'表示指令父元素应包含ng-model属性。

在您的情况下,您似乎错误地添加了^。我认为它应该是require: '^ngModel'

<强>指令

app.directive('myDirective', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
        ngModel: '='
    },
    template: '<span>see this ? {{ ngModel }}</span>',
    link: function(scope, element, attrs, ctrl){ //ctrl is nothing but the ngModel ctrl

    }
  }
});

<强> HTML

<div ng-app="myApp" ng-controller="MyCtrl" ng-init="content='Test'">
    <div my-directive ng-model="content"></div>
</div>

Working Fiddle