2

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.

enter image description here

1 Answer 1

3

I suspect that you have incorrect $watch expression. Which isn't firing your watcher function imageid scope variable change.

scope.$watch('imageid', function(value) {
     //....
});
Sign up to request clarification or add additional context in comments.

4 Comments

If i do console.log(scope.imageid); just below the $watch, i can see values. That means i have put watch on correct variable. I dont even know is it possible and right way to do it. So asking it on stackoverflow.
One more thing, console.log(scope.imageid); works when app loads and then when i first time click on individual "conatct", It doesnt run after that.
Have you tried changing your watcher expression, like i suggested??
I am so sorry, i though you got me wrong. Change you suggested worked perfectly. Thank!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.