javascript - Angular Directive(指令) - 更改模板内的数据

标签 javascript angularjs

我正在开发一个演示仪表板,在该仪表板内有标题。 我正在使用我的“标题”指令“生成”标题。 (希望到目前为止我做的是正确的)

app.js

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

header.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'
  };
});

attr link 的属性功能:

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

更新:

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

隔离范围:

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

attr link 的属性功能:

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

关于javascript - Angular Directive(指令) - 更改模板内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35195957/

相关文章:

javascript - 动态创建的用于下载文件的 iframe 会触发带有 Firebug 的 onload 但并非没有

javascript - 有条件的 JS 重定向

javascript替换由特殊字符组成的字符串

angularjs - 为什么找不到我的图像根目录

javascript - 什么是基于 Express 的框架?

php - iframe 在新标签页中打开

javascript - jQuery 组复选框问题

javascript - 这个例子中 "main" Controller 是如何访问$routeParams的?

javascript - 无法在 Node.JS 中检索 session

angularjs - 大写的 ACE 编辑器自动完成关键字