角度指令 - 更改模板内的数据

angular directive - change data inside the template

本文关键字:数据 指令      更新时间:2023-09-26

我正在开发一个演示仪表板,在该仪表板内有标题。我正在使用我的"标头"指令"生成"标头。(希望到目前为止我以正确的方式做到这一点)

应用.js

myapp.directive('header', function() {
    return {
        templateUrl: '../../partials/header.html'
    };
});

标头.html:

<h1>Logo</h1>
<span>{{breadcrumbs}}</span>

partials/dashboard.html

<header breadcrumbs="home"></header>

是否可以使用"痕迹导航"数据并将其传递到我加载的标题模板?

已尝试以下方法,但未成功:

myapp.directive('header', function() {
    return {
        breadcrumbs: 'for the sake of this example it can be static',
        templateUrl: '../../partials/header.html'
    };
});

存在两种实现目标的方法:

可以使用隔离作用域:

myapp.directive('header', function() {
  return {
    scope: {
      breadcrumbs: "@"
    },
    templateUrl: '../../partials/header.html'
  };
});

link函数attr属性:

myapp.directive('header', function() {
  return {        
    templateUrl: '../../partials/header.html',
    link: function(scope, element, attrs){
      scope.breadcrumbs = attrs.breadcrumbs
    }
  };
});

上级:

如果在属性 ( <header breadcrumbs="{{breadcrumbs}}"></header> breadcrumbs 中使用插值 ,上面的代码可以如下所示:

隔离范围:

myapp.directive('header', function() {
  return {
    scope: {
      breadcrumbs: "=" //two way binding
    },
    templateUrl: '../../partials/header.html'
  };
});

link函数的attr属性:

myapp.directive('header', function() {
  return {        
    templateUrl: '../../partials/header.html',
    link: function(scope, element, attrs){
      scope.breadcrumbs = scope.$eval(attrs.breadcrumbs) //eval interpolation value in this scope
    }
  };
});

是的,你可以这样做。

myapp.directive('header', function() {
  return {
    scope:{
      breadcrumbs: '@'
    },
    templateUrl: '../../partials/header.html'
  };
});

您可以直接在模板中使用breadcrumbs。无需在链接功能内执行任何操作。