Prabhu
Prabhu

Reputation: 13335

Angular directive not picking up the values set by parent

I have a directive that has a div, whose visibility is set by its parent. Expecting "show" to be true, but the div is still not visible initially on page load.

Directive:
<div ng-show="{{ show }}">
        ...
</div>

angular.module('myModule').directive('myDiv', [
  function () {
    return {
        scope: {
            show: '='
        },
        transclude: true,
        restrict: 'EA',
        controller: myController,
        controllerAs: 'ctrlr',
        templateUrl: 'myDiv.tpl.html'
    };
}]);

Parent:
<div myDiv show="ctrlr.shoudlShow()" ng-repeat="item in ctrlr.items">
</div>

There may be a possibility that shoudlShow() is returning false on page load, and later it turns true. Could it be that the directive myDiv is not picking up the latest values of shouldShow()? Do I need to watch for changes or anything?

Upvotes: 0

Views: 58

Answers (3)

Carlos Angarita
Carlos Angarita

Reputation: 311

You have a function called shoudlShow() and said function will return a boolean that will be passed to the directive. In this case you need to bind the variable that is returned to the directive, binding the function will not work. You could use something like

vm.isShown=vm.souldShow();

and then in your directive

<div myDiv show="ctrlr.isShown" ng-repeat="item in ctrlr.items">
</div>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

ng-show expects an expression not interpolation and you left out the controllerAs alias

Change to

<div ng-show="ctrlr.show">

A better approach would be to use a filter on ng-repeat instead or ng-if. Doesn't make sense adding all those elements (and the associated watches) if they aren't needed

Upvotes: 1

Greg Jeanmart
Greg Jeanmart

Reputation: 676

I don't understand exactly what you're trying to achieve, but When you create an Angular directive, The HTML attribute for a declared directive called myDiv should be my-div and not myDiv (see documentation)

Parent:
<div my-div show="ctrlr.shoudlShow()" ng-repeat="item in ctrlr.items">
</div>

Upvotes: 0

Related Questions