Skip to content

Instantly share code, notes, and snippets.

@rvillars
Last active March 22, 2016 12:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rvillars/d60d9416f2206c6e3407 to your computer and use it in GitHub Desktop.
Save rvillars/d60d9416f2206c6e3407 to your computer and use it in GitHub Desktop.
Preprocess directive attributes in AngularJS

Preprocess directive attributes in AngularJS

Sometimes you need to modify a two way binded attribute value prior to use it in the directive. This can't be done in the directive controller, because the attribute assignment is done after the controller is executed.

The link function is able to access the attributes directly but unfortunately a two way binded attribute expression isn't yet evaluated a that time.

The solution is to process the attribute in a scope.$watch function where the value will be evaluated automatically.

http://jsfiddle.net/gh/gist/angularjs/1.2.1/d60d9416f2206c6e3407/

<!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="angular.js@1.2.x" 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>
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';
}
});
},
};
});
name: Preprocess directive attributes in AngularJS
authors:
- Roger Villars
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment