Reputation: 3067
I'm still learning angularjs and today I wrote my second directive (hello world was the first).
I dont know whats wrong with plunkr. I couldn't able to setup AngularJS on plunkr. So sharing a image here. At least you will little idea.
What i am doing
I am building a contact list app, where I list users with pic, and when u click on user app shows its details, you can edit and add new user too. I'm fetching user pic from randomuser.me, for that I written a directive which is working fine. directive . Its working fine. Below is my code.
cbApp.directive('userPic', function() {
return {
restrict: 'E',
template: '<img class="circle" ng-src="https://randomuser.me/api/portraits/men/{{imageid}}.jpg">',
scope: {
imageid: '@'
},
}
});
When it goes wrong
I'm using same directive for "add contact" page. where it should show a default pic like "nouser.png", because there is no user id. Below is how I modified it.
cbApp.directive('userPic', function() {
return {
restrict: 'E',
template: '<img class="circle" ng-src="{{imgsrc}}">',
scope: {
imageid: '@'
},
link: function(scope, elem, attr){
scope.$watch(scope.imageid, function(value) {
if(scope.imageid){
scope.imgsrc = 'https://randomuser.me/api/portraits/men/'+value+'.jpg';
}
else
scope.imgsrc = appConstants.default_pic;
});
},
replace: true
};
});
Whats the actual problem
This binds image only once, and if I click on other user it doesnt load its image. If i click user 1 then in user details page i see "user 1" pic, then if I click on "user 2" it still shows "user 1" pic. When I try to add new user is should show "nouser.jpg" image it still shows "user 1" pic.
Upvotes: 2
Views: 210
Reputation: 136144
I suspect that you have incorrect $watch
expression. Which isn't firing your watcher function imageid
scope variable change.
scope.$watch('imageid', function(value) {
//....
});
Upvotes: 3