简体   繁体   中英

ng-Show doesn't work with directives

I have a directive which is shown (or should to) if "isEmpty" variable is true

// index.html
<div empty-notes-screen coleccion="Notes" ng-show="isEmpty"></div>

// directive.js
angular.module('myApp')
  .directive('emptyNotesScreen', function () {
    return {
        templateUrl: 'views/notes/emptynotesscreen.html', 
        replace: true,
        scope : {
            coleccion : '='
        },
        link : function (scope, elm,attrs){
            scope.$watchCollection('coleccion', function(newValue) {
                if(newValue.length>0){
                    scope.isEmpty = false;            
                }
                else{
                    scope.isEmpty = true;                   
                }
                console.log('isEmpty: ',scope.isEmpty);
                console.log(' coleccion has changed');
            });
        }
    };
  });


// views/notes/emptynotesscreen.html
<div class="white-text">
    <div  class="center grey darken-2" style="padding: 45px;">
        <img width="180px" src="images/ignotize-white.png">
        <h4>There's no notes yet!</h4>
        <p>Please, add a note at least to see it here.</p>
    </div>
</div>

Also, I have a controller that looks like this:

// scripts/index.js
angular.module('myApp')
  .controller('IndexNoteCtrl', function ($scope, NoteResource) {

    $scope.Notes = NoteResource.query();

  });

The result is, scope.isEmpty changes accordingly but in the HTML, the isEmpty never changes!! So that HTML never show or hide. I don't know why or where I am doing something wrong.

You are defining the variable isEmpty on the scope of the directive.

But you are trying to use this variable outside of the directive, where it has no value. You can fix this problem in at least two ways:

1) Move the ng-show so that it inside the template for the directive: <div class="white-text" ng-show="isEmpty">...</div>

2) Get rid of the watcher, and isEmpty and everything related to it. Then in your index.html where you use the directive use ng-show: ng-show="Notes.length >0"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM