Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

javascript - 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', 'taskFactory', '$state', 'imageTestService', function($scope, taskFactory, $state, imageTestService){

    $scope.taskData = {};
    $scope.current = 0;

    taskFactory.get().then(function(response){
        $scope.jsonData = response.data.data.resultCareGivers;
    });

    $scope.back = function(){
        $scope.current = ($scope.current !== 0 ? $scope.current - 1 : 0);
    };

    $scope.next = function(){
        $scope.current = ($scope.current !== $scope.jsonData.length-1 ? $scope.current + 1 : $scope.jsonData.length-1);
    };

}]);

and a Directive to verify image loading:

app.directive('imageTestDirective', function($http){
   return {
       restrict: 'A',
       link: function($scope, elem, attrs){

           attrs.$observe('ngSrc', function(ngSrc){
                if(ngSrc != null && ngSrc != ""){
                    $http.get(ngSrc).then(function(success){
                      $scope.noImage = false;
                       console.log('success loading image', success);
                    }, function(error){
                        $scope.noImage = true;
                        console.log('error loading image', error);
                    });
                }
           });
       }
   }; 
});

Html with attribute directive and next and back button to cycle through json:

<img image-test-directive ng-show="noImage === false"  ng-src="{{jsonData[current].profilepic}}"  alt=""/>

<div ng-if="noImage">
    <div>{{jsonData[current].firstName.charAt(1)+jsonData[current].lastName.charAt(1)}}</div>
</div>

<div class="col-xs-12">
    <div class="col-xs-2">
        <button type="button" ng-click="back()">Back</button>
    </div>

    <div class="col-xs-6" style="text-align: right">
        <button type="button" ng-click="next()">Next</button>
    </div>
</div>

The problem is the directive works on page load and the image is loaded properly, but I when I navigate through json object to view details, the directive is not evaluated (I mean when there no image inside json, it should show firstName+lastName)

How do I achieve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 /* ... */) {

    function MyNewJSON(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;
       /* ... */
    }

    function getNewJSON(){
     return new MyNewJSON(origJSON); // it might be promise and you need resolve it in controller
    }

}]);

So your HTML should look like:

<img ng-if="stateData.hasImage"  ng-src="stateData.profilepic"  alt=""/>

<div ng-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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...