Angular directive - changing data inside a template

I am working on a demo panel and there is a title bar inside this panel. I “generate” the header using my “header” directive. (Hope I'm doing it right so far)

app.js

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

header.html:

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

partial /dashboard.html

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

Is it possible to use the breadcrumbs data and deliver it to the header template that I am loading?

Tried the following without success:

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

There are two ways to achieve the goal:

you can use an isolated area:

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

or attrfunction attribute link:

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

UPD:

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

, .

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

breadcrumbs . .

+1

Source: https://habr.com/ru/post/1627255/


All Articles