2014-12-04 27 views
0

我有一個顯示一些信息的輸入字段:angularjs數據變換

<input type="text" id="1" data-transformer="" data-ng-model="number"/> 

我需要的是根據例如一些變量來改變顯示的信息:

「數量」模型是等於值10.我也有動態變量「x」,範圍0-24。條件是:如果「x> 23」,那麼而不是原來的「數字」模型值10,我需要顯示「 - 」。

我認爲這將使用額外的指令是可能的「數據變壓器=」「」

mbg.directive('transformer', function() { 
    return { 
     require: 'ngModel', 
     link: function (s, e, a, m) { 
      m.$formatters.unshift(function (model) { 
       s.tmp = model; 
       return (s.x > 23 ? '--' : model); 
      }); 

      m.$parsers.push(function() { 
       return s.tmp; 
      }); 
     } 
    }; 
}); 

然而,這並不工作,我想:它只能在第一時間,頁面加載和「x」被設置,但是如果「x」值改變什麼都沒有發生。我有點理解爲什麼它是這樣的(這是因爲變形指令只在「數字」模型改變時才起作用,而不是「x」)。

我想知道,我如何達到我需要的結果?

+0

看變量x,如果x> 23更改數字的值 – 2014-12-04 07:14:24

+0

您可以使用控制器中的函數來執行指令,而不是使用指令。或者你可以使用$ watch。 – Ved 2014-12-04 07:16:26

+0

這將工作,但我需要有數字的真正價值。我需要的是有一個信息並顯示其他信息,例如symfony2格式的數據轉換器。 – 2014-12-04 07:22:10

回答

0

您可以用過濾解決它,如果你能在一個非輸入元素存在的數量,或者你可以使用一個手錶和綁定您的輸入NG-模型變換表示:)

http://jsfiddle.net/HB7LU/8784/

HTML

Input: <input data-ng-model="number" /> 
<hr> 
<h2>Filter</h2> 
<span ng-bind="number | transformer"></span> 
<hr> 
<h2>Watch</h2> 
<div ng-controller="transformerController"> 
    <input ng-model="transformedNumber" readonly /> 
</div> 

JS

var myApp = angular.module('myApp',[]); 

myApp.filter('transformer', function() { 
    return function (input, target) { 
     return (input > 23 ? '--' : input); 
    } 
}); 


myApp.controller('transformerController', ['$scope', function ($scope) { 
    $scope.$watch('number', function(value) { 
     $scope.transformedNumber = (value > 23 ? '--' : value); 
    }); 
}]); 
+0

有趣的方法,我寧願第一個解決方案,因爲它更清潔,但我確實需要輸入字段。第二種解決方案很有趣,但是如何將該值轉換回原來的值?並且我需要用一點不同的邏輯來轉換這個值「(x> 23?' - ':value)」我將如何得到「x」的值? – 2014-12-04 08:24:05

+0

原始值在$ scope.number上可用,並且轉換可在$ scope.transformedNumber上使用。您可以更改手錶內的登錄名,其值爲$ scope.number。 – 2014-12-04 09:05:51