2013-09-24 61 views
0

HTML濾波器輸入與指令

<input type="text" name="usernr" ng-model="userNr" placeholder="user nr" 
           tabindex="2" ng-usernumber/> 

的JavaScript

app.directive('ngUserNumber', function() { 
      return { 
       restrict: 'A', 
       require: 'ngModel', 
       link: function(scope, elm, attrs, ctrl) { 
        console.log("inside directive"); 
        ctrl.$parsers.push(function(data) { 
         console.log("//convert data from view format to model format"); 

         data = data.toString() + " test"; 

         return data; //converted 
        }); 

        ctrl.$formatters.push(function(data) { 
         console.log("//convert data from model format to view format"); 

         data = data.toString() + " test"; 

         return data; //converted 
        }); 
       } 
      }; 
     }); 

我想從裏面指令取代伍模型提供的數據,與數據。但沒有任何反應。如何不使用自定義指令?

我跟着這個文檔:http://www.ng-newsletter.com/posts/directives.html
其它來源:https://stackoverflow.com/a/15346236/489856

+0

鏈接函數是否被調用\執行? – Chandermani

+0

否(日誌未執行) – Vincent

+2

您在html中的指令名應該是'mg-user-number' – Chandermani

回答

1

這樣做只是這樣的:

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

app.controller('MyCtrl', function($scope){ 

    }); 

app.directive('ngUsernumber', function() { 
      return { 
       restrict: 'A', 
       require: 'ngModel', 
       link: function(scope, elm, attrs, ctrl) { 

        var format = function(data){ 
         console.log("//convert data from view format to model format"); 

         if(data !== undefined){ 
          data = data.toString() + " test"; 
         } 


         return data; //converted 
        }; 

        ctrl.$parsers.push(format) 
        ctrl.$formatters.push(format); 

       } 
      }; 
     }); 

工作plunkr這裏:http://plnkr.co/edit/iA85KC?p=preview

你必須尊重駝峯匹配您的指令注意:ngUsernumber - > ng-usernumber(如果你是ngUserNumber) - > ng-user-number

希望它有幫助!

+0

你的plnkr,看起來不錯。但「測試」不附加? – Vincent

+0

我已經更新了plunlkr,如果你看下輸入好字符串是打印 –

+0

ng-model =雙綁定。那麼爲什麼只有段落顯示「yourtypedstring test」並且inputfield不會將測試添加到ng-Model? – Vincent