2015-04-01 65 views
2

我們正在創建一個指令,用於在用戶單擊按鈕時增加和減少文本框中的數字。指令永遠不會被調用angularjs

這是我的自定義指令的代碼。

var CEDirectives = angular.module('App.customnumberdirectives', []) 
.directive('ngcustomNumber', ['$compile', function ($compile) { 
var TEMPLATE_URL = '/customnumber/index.html'; 
var tem = '<div class="wrapper">' + 
      ' <input type="text" data-ng-model="{{model}}" data-ng-blur="onBlurHandler()">' + 
      ' <button ng-click="Increase()" style="cursor:pointer; background-color: transparent">INC</button>' + 
      ' <button ng-click="Decrease()" style="cursor:pointer; background-color: transparent">DEC</button>' + 
      '</div>'; 

// Set the default template for this directive 
$templateCache.put(TEMPLATE_URL,tem); 

return { 
    restrict: "E", 
    scope: { 
     model: '@', 
     onblurevent: '&' 
    }, 
    replace: true, 
    templateUrl: function (element, attrs) { 
     return attrs.templateUrl || TEMPLATE_URL; 
    }, 
    link: function (scope, element, attributes) { 

     scope.onBlurHandler = function() { 
      if (scope.onblurevent) { 
       scope.onblurevent(); 
      } 
     }; 

     scope.Increase = function() { 
      alert('Inc'); 
     }; 
     scope.Decrease = function() { 
      alert('Dec'); 
     }; 
    } 
}; 
} ]); 

在HTML視圖: -

<ngcustomNumber model="weight" onblurevent="Save"></ngcustomNumber> 

(1)否在控制檯錯誤。

(2)試圖把警報置於指令的頂端。沒有警報消息出現。

在此先感謝!

+0

甲肝,你在你的HTML – 2015-04-01 06:30:11

+1

是應用ngApp。它在HTML標籤中。 – 2015-04-01 06:31:47

+0

App.customnumberdirectives是您的模塊名稱只是爲了確認? – 2015-04-01 06:32:30

回答

0

試試這個:

<ngcustom-number model="weight" onblurevent="Save"></ngcustom-number> 
+0

ngcustomNumber和ngcustom-number工作相同 – 2015-04-01 06:33:50

+0

工作。但是我可能知道用相似的方式寫指令是否是強制性的? – 2015-04-01 06:36:05

+0

你已經設置了'restrict:'E'',這意味着只有元素是允許的。使用'AE',否則如果你想使用屬性 – Chandermani 2015-04-01 06:36:56

0

因爲你的編譯沒有右way.You做必須確保給定的範圍是template.For檢查它,你可以打印範圍ID在template.As你知道每因爲如果指令範圍和模板範圍ID不一樣,那麼你的問題在於它,並且解決方案是:

以正確的方式編譯它,並在其中傳遞你的指令的作用域。 $ compile服務:$ compile(template)(directiveScope);

,你可以安慰範圍,將看到的領域我在談論

相關問題