Simplify repeated scope attributes in angularjs

I found myself repeating the following structure too often and I'd like to simplify it:

<container>
  <clock property="data"></clock>
  <calendar property="data"></calendar>
  <alert property="data"></alert>
</container>

With the relative directive

app.directive('clock', function(){
  return {
    restrict: 'E',
    scope: {
      'property': '='
    }
  }
});

How could I remove the property="data" from each item and move it eventually at the container level?

Answers


You can set property="data" in parent directive and make it available through its controller

Your container directive

<container property="data">

app.directive('container', function(){
  return {
    restrict: 'E',
    scope: {
      'property': '='
    },
    controller: function($scope){
      this.getData = function(){
        return $scope.property;
      }
    }
  }
});

And your child directive

<clock></clock>    

app.directive('clock', function(){
  return {
    restrict: 'E',
    require: '^container',
    link: function(scope, elm, attrs, containerCtrl) {
      console.log(containerCtrl.getData());
    }        
  }
});

require the parent directive and call it's associate method containerCtrl.getData() to get your required value.

Check the Demo


Need Your Help

ApacheTop for Windows

windows apache logging monitoring

I'm running Apache on Windows 7 x64.

WCF - remote service without using IIS - base address?

wcf asmx endpoints addressing

I'm trying to get my head around the addressing of WCF services.