Reputation: 788
I have the following directive to show alerts, so I want catch when the show varible change to star run a timeout how I can do that?
the link function was invoked only the first time but all variable show, message and type was undefined
Directive code
angular.module('pysFormWebApp')
.directive('alertDirective',
function alertDirective ($timeout) {
return {
restrict : 'E',
scope : {
message : "=",
type : "=",
show : "=",
test : "="
},
controller : function ($scope) {
$scope.closeAlert = function () {
$scope.show = false;
$scope.type = "alert alert-dismissable alert-";
$scope.message = "";
};
$scope.getStrongMessage = function (type) {
var strongMessage = "";
if(type == "success"){
strongMessage = "\xC9xito ! ";
} else if(type == "warning"){
strongMessage = "Cuidado ! ";
return strongMessage;
}
},
link: function(scope, element, attrs) {
scope.$watch(scope.show,
function (newValue) {
console.log(newValue);
},true);
},
templateUrl : "views/utilities/alert.html"
};
});
html directive code
<div ng-show="show">
<div class="alert alert-dismissable alert-{{type}}">
<button type="button" class="close" ng-click="closeAlert()">×</button>
<strong>{{getStrongMessage(type)}}</strong> {{ message | translate }}
</div>
</div>
Controller example
$scope.info.alert = {
message: "EXPOTED-SUCCESS",
type: "success",
show : true
};
html code
<alert-directive message="info.alert.message"
type="info.alert.type"
show="info.alert.show">
</alert-directive>
Upvotes: 1
Views: 186
Reputation: 136144
You have make mistake while setting watch on the scope variable. Basically $watch
takes 1st parameter as string
/function
which gets evaluated on each digest cycle & 2nd parameter would be the callback function
//replaced `scope.show` by `'show'`
scope.$watch('show', function (newValue) {
console.log(newValue);
},true);
Upvotes: 1