簡體   English   中英

單擊角時評估或調用指令

[英]Evaluate or call directive on click in angular

我正在嘗試從json加載圖像,如果圖像不可用,請顯示名字和姓氏。

我有這樣的控制器:

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);
    };

}]);

以及驗證圖片加載的指令:

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和下一個和后退按鈕以循環遍歷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>

問題是該指令在頁面加載時有效並且圖像已正確加載,但是當我瀏覽json對象以查看詳細信息時,該指令未評估(我的意思是當json中沒有圖像時,它應該顯示firstName + lastName)

我該如何實現?

我認為您為此用例編寫的邏輯過於復雜。

用基本的詞來說,從服務器獲取的JSON包含一些帶有/不帶有圖片URL或帶有損壞的圖片URL的數據。

因此,要使HTML變得復雜,只需將您的JSON嵌入服務並將新的JSON引入您的控制器即可。

例如:

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
    }

}]);

因此,您的HTML應該如下所示:

<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>

無需指令。


由於圖像驗證可能需要一些時間,因此您可以放置​​默認圖像(某種占位符)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM