将指令作用域值绑定到HTML

Binding Directive Scope Value to HTML

本文关键字:HTML 绑定 指令 作用域      更新时间:2023-09-26

我正在处理AngularJS指令。此指令具有一些自定义属性。我将使用这样的指令:

<my-directive show-links="false" />

show-links是一个属性,如果开发人员没有专门设置它,我想默认为true

.directive('myDirective', function () {
  return {
    restrict:'E',
    transclude: true,
    scope: {
      showLinks: '=?'
    },
    templateUrl: '/directives/my-directive.html',
    controller: function ($scope) {
      if (angular.isUndefined($scope.showLinks)) {
        $scope.showLinks = true;
        console.log('show links? ' + $scope.showLinks);
      }
    }
  };
});

My-directive.HTML中的HTML如下所示:

<div><h1>Hello! {{showLinks}}</h1></div>
<div ng-if="showLinks == true"">
  <a href='#'>do something</a>
</div>

当这个指令被评估时,我可以在控制台窗口中看到"show links?true"。然而,在屏幕上,我看不到"你好"一词旁边印着"真"。这就像HTML在showLinks进入作用域之前被渲染一样。我做错了什么?

我记得隔离范围有问题-解决方案是将隔离范围对象中的任何内容添加到指令HTML代码本身中,如下所示:

.directive('widgetRecentEntries', function(){
        return {
            restrict: "E",
            replace: true,
            scope: {
                recents: "=recents"
            },
            templateUrl: "ngapp/js/tpl/widget-recent-entries.html"
        };
    })

指令HTML/模板:

<dl class="dl-horizontal flip-in" ng-repeat="item in recents" recents="recents">
    <dt>
    <a href="/{{item.seo_name}}.html">
        <img src="{{item.logo_url}}" alt="" width="80">
    </a>
</dt>
<dd>
    <p><a href="/{{item.seo_name}}.html">{{item.name}}</a></p> 
</dd>
</dl>