Skip to content Skip to sidebar Skip to footer

Evaluate Or Call Directive On Click In Angular

I am trying to load an image from json and if image is not available, then show firstname and lastname. I have controller like this: app.controller('task1Controller',['$scope', 'ta

Solution 1:

I think you wrote the logic too complicated for this use case.

In basic words JSON you get from Server contains some data with/without image URL or with broken image URL.

So instead to make HTML to be complicated, just embed your JSON in service and bring new JSON to your controller.

for example:

app.service('SomeService',['$q', /* ... */function ($q /* ... */) {

    functionMyNewJSON(origJSON){
      // check here if origJSON contains wrong image url // and set new JSON key hasImage = true or false by validating it here in service and not in directive.this.hasImage = true;
       /* ... */
    }

    functiongetNewJSON(){
     returnnewMyNewJSON(origJSON); // it might be promise and you need resolve it in controller
    }

}]);

So your HTML should look like:

<imgng-if="stateData.hasImage"ng-src="stateData.profilepic"alt=""/><divng-if="!stateData.hasImage"><div >{{stateData.firstName.charAt(1)+stateData.lastName.charAt(1)}}</div></div>

No directive needed.


Since image validation can take some time, you can put default image (some kind of placeholder)

Post a Comment for "Evaluate Or Call Directive On Click In Angular"