Martijn Martijn - 1 year ago 65
AngularJS Question

How to prevent that a scope is shared among directives n Angular?

All my directives use the same scope and I want my directives to operate by their own.


app.directive('headerSort', function () {
return {
restrict: 'A',
controller: function ($scope, $element, $attrs) {
$scope.caption = $attrs.caption;

$scope.doSort = function () {
$scope.orderField = $attrs.headerSort;
$scope.reverse = !$scope.reverse;
template: '<div data-ng-click="doSort();">' +
'{{caption}}' +
'<i class="icon-sort"></i>' +


<th data-header-Sort="FullName" data-caption="Full name"></th>
<th data-header-Sort="FirsName" data-caption="First name"></th>
<th data-header-Sort="Age" data-caption="Age"></th>

The result is that all the columns has the value 'Age' and sort by Age. I want of course that every column sort it's own column. How can I achieve this?

Forgot to mention that
are used in the
ng-repeat | orderBy

<tbody id="customerRows" data-ng-repeat="customer in customers | orderBy:orderField:reverse">

Answer Source

Each instance of your directive needs to have its own caption, sort type, and reverse property. So the directive will need its own (child) scope — either an isolate scope (scope: {}) or a new scope (scope: true). Since the directive is not a standalone/self-contained component, I would not use an isolate scope (see also When writing a directive, how do I decide if a need no new scope, a new child scope, or a new isolate scope?).

With the type of scope selected for the directive, the sort type and reverse values can be passed to the parent via function arguments, or they can be set on parent scope directly. I suggest function arguments:

app.directive('headerSort', function () {
    return {
        scope: true,   // creates a new child scope
        link: function (scope, element, attrs) {
            scope.caption  = attrs.caption;
            scope.sortType = attrs.headerSort;
            scope.reverse  = false;
        template: '<div data-ng-click="reverse=!reverse; doSort(sortType, reverse);">' +
function MyCtrl($scope) {
    $scope.orderField = "FirstName";
    $scope.reverse    = false;
    $scope.customers  = [ {FirstName: 'Martijn', Age: 22}, {FirstName: 'Mark', Age: 44}];
    $scope.doSort = function (sortType, reverse) {
        console.log('sorting',sortType, reverse);
        $scope.orderField = sortType;
        $scope.reverse    = reverse;
    <th data-header-sort="FirstName" data-caption="First name"></th>
    <th data-header-sort="Age" data-caption="Age"></th>
    <tbody id="customerRows" data-ng-repeat="customer in customers | orderBy:orderField:reverse">

fiddle In the fiddle, just for simplicity, I did not include the FullName column.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download