Question

I was using angular growl, which is quite good for showing message. (https://github.com/marcorinck/angular-growl)

It OK to add a message in a controller, but when add a message in a directive, it's not show, why? Here is my test code.

a.html

<?xml version="1.0" encoding="UTF-8" ?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css"     href="https://raw.github.com/marcorinck/angular-growl/master/src/growl.css" />

<script type="text/javascript" src="../lib/angular/angular.js"></script>
<script type="text/javascript" src="../lib/angular-growl/angular-growl.js">    </script>
<script type="text/javascript" src="../lib/angular-route/angular-route.js">    </script>
<script type="text/javascript" src="a.js"></script>
</head>
<body>
<div ng-view=""></div>
<div growl="" class='growl-container'></div>
</body>
</html>

a.js

'use strict';

var module = angular.module('a', ['ngRoute', 'angular-growl']);
module.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
    controller: 'IndexCtrl',
    template: '<button aaa>aaaa</button>'
});
}]);

module.controller('IndexCtrl', ['growl', function (growl) {
growl.addErrorMessage('haha');
}]);

module.directive('aaa', ['growl', function (growl) {
return {
    restrict: 'A',
    scope: {},
    link: function (scope, element, attrs) {
        element.bind('click', function (e) {
            console.log('aaa');
            growl.addErrorMessage('aaa');
            growl.addErrorMessage('bbb');
        });
    }
};
}]);

var $html = angular.element(document);
$html.ready(function () {
angular.bootstrap($html, ['a']);
$html.addClass('ng-app');
});
Was it helpful?

Solution

Whenever you have events outside of angular that change angular scopes you need to use $apply to inform angular that changes are made and to run a digest cycle.

If you were to use ng-click instead you wouldn't run into this problem.

To resolve with current external event code:

element.bind('click', function (e) {
       scope.$apply(function(){
            growl.addErrorMessage('aaa');           
      })
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top