Preprocess directive attributes in AngularJS

author(s): Roger Villars

HTML

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MyCtrl">
    <input ng-model="myScopeValue">
    <my-directive my-attribute="myScopeValue"></my-directive>
  </body>

</html>

JavaScript

var app = angular.module('myApp', []);

app.controller('MyCtrl', function($scope) {
  $scope.myScopeValue = 'Delete me';
});

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      myAttribute: '='
    },
    controller: function ($scope, $element) {
      // this won't work because the attribute is initialized after the controller
      if ($scope.myAttribute === '') {
        $scope.myAttribute = 'Changed by controller';
      }
    },
    template: '<p>{{myAttribute}}</p>',
    link: function (scope, element, attributes) {
      scope.$watch('myAttribute', function (value) {
        if (value === '') {
          scope.myAttribute = 'Changed by link';
        }
      });
    },
  };
});