Saqueib
Saqueib

Reputation: 3520

why scope is not updating once changed by directive in ionic

I have a simple directive which shows notification, user can tap on it to close it. its not working as expected (once hide by user its not showing again) in ionic, and same thing it working on angular only.

Angular Demo

Ionic CodePen

Here is directive code

angular.module('app').directive('notificationBar', [function(){
return {
    restrict : 'A',
    scope : {
      msg : '@',
      type : '@',
      show : '='
    },
    template : '<div ng-click="hideIt()" ng-show="show" class="alert {{type}}"><span>&times;</span> {{ msg }}</div>',
    link : function ( scope, elem, attr ) {
      scope.type = attr.type || 'alert-danger';

      scope.hideIt = function () {
          scope.show = false;
      };

      // for debugging 
      scope.$watch('show', function(newValue, oldValue) {
        console.info('old show val', oldValue);
        console.info('new show val', newValue);
      });

     }
   };
}]);

Upvotes: 0

Views: 76

Answers (1)

Chanthu
Chanthu

Reputation: 1794

Looks like dot rule in angular js is to blame here. Because error is a primitive value, once that's changed in the controller scope, the variable that directive is watching for is referring to old value.

Why is this different between web and ionic, not sure. But to solve this, warp error inside an object and user dot notation to access it.

Like so:

$scope.error = {
   error: true
};

<div notification-bar show="error.error" msg="Something is wrong here :( " type="alert-danger"></div>

Here's the updated code pen: http://codepen.io/anon/pen/BjrRRJ?editors=1011

For more information on this dot rule I mentioned, here's a good stackoverflow post which is worth reading: https://stackoverflow.com/a/17607794/841804 and https://stackoverflow.com/a/14049482/841804

Upvotes: 2

Related Questions