2016-06-09 4 views
1

Я возвращаю объекты из базы данных Sqlite, которая иногда возвращает null для некоторых атрибутов этого объекта. Например (item.unit) иногда имеет нулевое значение в базе данных.Ng-Model возвращает null вместо нуля

Я получил этот код в моем HTML файл

<td class="item-row-quote"><span class="quote-price-text" ng-model="row.dollarPerUnitText" 
               id="dollarPerUnit">{{ '$/' + item.unit }}</span></td> 

Как я могу убедиться, что дисплей браузера ничего для item.unit вместо отображения пустой.


Это мой код контроллера

angular.module('canex') 
.controller("QuoteController", ['$scope', '$routeParams', '$location', 'ProjectService', 'QuoteService', 'UploadService', 'ClientService', 'ItemService', 'ConditionService', 
    function ($scope, $routeParams, $location, projectService, quoteService, uploadService, clientService, itemService, conditionService) { 
     $scope.clientId = $routeParams.clientId; 
     $scope.projectId = $routeParams.projectId; 
     $scope.quoteId = $routeParams.quoteId; 
     $scope.IMG_URL = uploadService.getImageUrl(); 
     $scope.quoteDate = new Date().getFullYear().toString().substr(2, 2); 
     $scope.items = []; 


     function _fetchQuote() { 
      quoteService.getQuote($routeParams.quoteId) 
       .then(function (response) { 
        $scope.quote = response.data; 
       }, $scope.httpErrorCallback); 
     } 

     function _fetchItems() { 
      itemService.getQuoteItems($routeParams.quoteId) 
       .then(function (response) { 
        $scope.items = response.data; 
       }, $scope.httpErrorCallback); 
     } 

     function _fetchConditions() { 
      conditionService.getQuoteConditions($routeParams.quoteId) 
       .then(function (response) { 
        $scope.conditions = response.data; 
       }, $scope.httpErrorCallback); 
     } 


     function _fetchClient() { 
      clientService.getClient($routeParams.clientId) 
       .then(function (response) { 
        $scope.client = response.data; 
       }, $scope.httpErrorCallback); 
     } 

     function _fetchProject() { 
      projectService.getProject($routeParams.projectId) 
       .then(function (response) { 
        $scope.project = response.data; 
       }, $scope.httpErrorCallback); 
     } 


     $scope.addRow = function() { 
      $scope.items.data.push({}); 
     }; 

     $scope.addCondition = function() { 
      if (document.getElementById("condition-page").style.display == "none") { 
       document.getElementById("condition-page").style.display = ''; 
      } 
      $scope.conditions.data.push({}) 
     }; 

     $scope.removeRow = function (index) { 
      var itemId = $scope.items.data[index].id; 
      itemService.archiveItem(itemId); 
      $scope.items.data.splice(index, 1); 
     }; 

     $scope.removeCondition = function (index) { 
      var conditionId = $scope.conditions.data[index].id; 
      conditionService.archiveCondition(conditionId); 
      $scope.conditions.data.splice(index, 1); 
     }; 

     $scope.subtotal = function() { 
      var subtotal = 0; 
      angular.forEach($scope.items.data, function (item) { 
       subtotal += item.quantity * item.rate; 
      }); 
      return subtotal; 
     }; 

     $scope.generateQuote = function (divName) { 
      $scope.submitItems(); 
      $scope.submitConditions(); 
      if ($scope.conditions.data.length == 0) { 
       document.getElementById("condition-page").style.display = "none"; 
      } 
      var printContents = document.getElementById(divName).innerHTML; 
      var popupWin; 
      if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { 
       popupWin = window.open('', '_blank', 'width=600,height=800,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no'); 
       popupWin.window.focus(); 
       popupWin.document.write('<!DOCTYPE html><html><head>' + 
        '<link rel="stylesheet" type="text/css" href="../css/style.css" />' + 
        '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></html>'); 
       popupWin.onabort = function (event) { 
        popupWin.document.close(); 
        popupWin.close(); 
       } 
      } else { 
       popupWin = window.open('', '_blank', 'width=800,height=600'); 
       popupWin.document.open(); 
       popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="../css/style.css" /></head><body onload="window.print()">' + printContents + '</html>'); 
       popupWin.document.close(); 
      } 
      popupWin.document.close(); 
      return true; 
     }; 

     $scope.submitItems = function() { 
      angular.forEach($scope.items.data, function (item) { 
       if (item.quote_id == undefined) { 
        delete item.$$hashKey; 
        item.quote_id = $routeParams.quoteId; 
        itemService.createItem(item); 
       } 
      }); 
     }; 

     $scope.submitConditions = function() { 
      angular.forEach($scope.conditions.data, function (condition) { 
       if (condition.quote_id == undefined) { 
        delete condition.$$hashKey; 
        condition.quote_id = $routeParams.quoteId; 
        conditionService.createCondition(condition); 
       } 
      }) 
     }; 

     _fetchItems(); 
     _fetchConditions(); 
     _fetchQuote(); 
     _fetchClient(); 
     _fetchProject(); 


    }]) 
.directive('elastic', [ 
    '$timeout', 
    function ($timeout) { 
     return { 
      restrict: 'A', 
      link: function ($scope, element) { 
       $scope.initialHeight = $scope.initialHeight || element[0].style.height; 
       var resize = function() { 
        element[0].style.height = $scope.initialHeight; 
        element[0].style.height = "" + (element[0].scrollHeight + 10) + "px"; 
       }; 
       element.on("input change", resize); 
       $timeout(resize, 0); 
      } 
     }; 
    } 
]); 
+0

Возможно, вы можете использовать фильтр. – Nico

+1

позволяет нам видеть ваш код контроллера. эта логика должна быть решена там. – adolfosrs

+0

Я добавил его для вас. –

ответ

1

Вы можете использовать ng-show Somthing как:

<td class="item-row-quote"> 
<span ng-show = "item.unit != null" class="quote-price-text" ng-model="row.dollarPerUnitText" id="dollarPerUnit">{{ '$/' + item.unit }}</span></td> 

Я надеюсь, что это то, что вы имеете в виду nothing не ясно.

+0

Да, спасибо, он работает! Извините, если я не был ясен –

+0

Знаете ли вы, почему мой вопрос не поддерживается? @itsik Я пытаюсь задать хорошие вопросы о stackoverflow и таких людей, как вы, даете хорошие ответы, но я все равно получаю downvoted. –

+0

Вы добавили в соответствие трески, будьте более конкретными и убедитесь, что первый раз читатель полностью вас поймет. –

0

Если у вас есть одно или два свойства, которые могут иметь нуль, то вы можете обновить их пустыми строками в контроллере.

DefaultController.$inject = ['$http']; 

function DefaultController($http) { 
    var vm = this; 
    vm.item; 

    function getItem() { 
     var config = { 
      transformResponse: function(data, headers) { 
       if (data) { 
        if (data.unit === null || data.unit === undefined) { 
         data.unit = ''; 
        } 
       } 

       return data; 
      } 
     }; 

     $http.get('/api/items', config) 
      .success(getItemCompleted); 

     function getItemCompleted(data) { 
      vm.item = data; 
     } 
    } 
} 

Если у Вас есть много свойств, которые могут быть нулевыми, и если у вас есть контроль на стороне сервера кода, а затем увидеть, если вы можете справиться там, вернув пустые массивы или пустой список, но не нулевое значение, если не то напишите настраиваемый фильтр, в котором вы можете прокручивать все свойства объекта и назначать пустую строку любому свойству, которое является ложным значением.

+0

Спасибо, но я думаю, что для этого приложения лучше использовать только ng-show с условием. –

+0

Знаете ли вы, почему мой вопрос не поддерживается? Я стараюсь задавать хорошие вопросы о stackoverflow и таких, как вы, даете хорошие ответы, но я все равно получаю downvoted. –