2014-05-25 36 views
0

我有字符串文本,我想根據屏幕寬度顯示我隱藏了多少個字如何根據元素寬度截斷文本,角?

這是我到目前爲止有:

app.filter('words', function() { 
     return function (input, words) { 
      if (isNaN(words)) return input; 
      if (words <= 0) return ''; 
      if (input) { 
       var inputWords = input.split(/\s+/); 
       if (inputWords.length > words) { 

        var theLength = inputWords.length - words; 

        input = inputWords.slice(0, words).join(' ') + ' + ' + theLength; 
       } 
      } 
      return input; 
     }; 
    }); 

這個濾鏡單詞的固定數。如果words = 5表示我們只能看到5個單詞,其他將被隱藏。

但我正在尋找的方式,使words號碼動態根據元素的寬度。例如對於<div>寬度200像素我顯示12個單詞,(也許更多也許更少),爲40px - 或零字(如果字太長)或一個字,

我想我需要混合一些指令,應該元素寬度並計算words數字。

這是一個演示:

DEMO

enter image description here

非常感謝您的幫助,

回答

3

這裏有一個指導我掀起了:

app.directive('wordCount', function($compile){ 
    return{ 
     restrict: 'E', 
     replace: true, 
     scope: { 
      width: '=', 
      text: '=' 
     }, 
     template: '<div style ="border-style: solid; width:{{width}}px"><span>{{text}}</span></div>',   
     link: function(scope, element, attrs){    
      scope.$watch('width', function(value){   
       if(isNaN(scope.width) || scope.width < 0) 
        return; 
       var numWords = Math.floor(scope.width/15); 
       var inputWords = scope.text.split(/\s+/); 
       var theLength = inputWords.length - numWords; 
       console.log('Element width: ' + scope.width); 
       console.log("# of words: " + inputWords.length); 
       console.log("# of words to show: " + numWords); 

       element[0].innerHTML = inputWords.slice(0, numWords).join(' ') + ' + ' + theLength;   
      }); 
     } 
    }; 
}); 

邏輯全部在link函數中,它大多使用您自己的代碼。用法是這樣的:

<word-count width="<width>" text="<text>"></word-count> 

其中<width>是你想要的格是寬度,<text>是你要顯示的文字。我用一個簡單的公式width/15來確定要顯示的單詞數量。你可能想要提出一些更復雜的東西。

這是一個Fiddle顯示它的行動。

+0

謝謝你隊友,偉大的工作! – snaggs

+0

順便說一句,你平均字長'scope.width/15',這是有些情況下,這種邏輯錯誤 – snaggs

+0

我只是從一頂帽子拉出該公式。無論如何,我想你會想出自己的想法。 – Jerrad