1

When I update parent scope variable from custom directive by calling a function from directive then directive dom is not updated. In this example $scope.ascending is true, and sort() function do toggle its value. I am calling sort function from both parent view as well as from child(directive), but change is not reflected in directive template. run this code as is to see the issue

HTML

<html ng-app="sortApp">
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
        <script src="testApp.js"></script>
    </head>
    <body>
        <div ng-view>
            <div ng-controller="sortController">
                <span>Parent scope: sorting order: </span>"{{ascending ? 'a->z' : 'z->a'}}"
                <br /><br />
                <div><input type='button' value='toggal sort order from parent' ng-click='sort()' /></div><br/>
                <sorting-from-directive asc="ascending" sort-action="sort()"> </sorting-from-directive>
            </div>
        </div>
    </body>
</html>

CODE

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

app.controller('sortController', function ($scope) {

    $scope.ascending = true;

    $scope.sort = function () {

        $scope.ascending = !$scope.ascending;
    }

});

app.directive('sortingFromDirective', function () {

    return {
        restrict: 'EA',
        scope: {
            asc: '=',
            sortAction: '&'
        },
        template: "<div><input type='button' value='toggal sort order from directive' ng-click='sortAction()'/> <span>Child scope: sorting order:</span><span ng-show={{asc}}>a->z</span> <span ng-hide={{asc}}>z->a</span></div>"
    };
});
Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74
  • the directive creates it's own scope, so the directive is updating `ascending` in it's own scope, not the parent controller. This is a *very common* issue, and the main reason that you should **always use a dot in angular bindings** (meaning bind to an object property, not a primitive). see [How prototype inheritance works with angular scope](http://stackoverflow.com/a/14049482/2495283) – Claies Mar 30 '17 at 21:44

1 Answers1

0

You shouldn't be using {{}}(interpolation) inside ng-show/ng-hide

<span ng-show='asc'>a->z</span> 
<span ng-hide='asc'>z->a</span>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299