2015-11-06 38 views
0

我想製作一個自定義指令,它將顯示基於屬性存在的不同按鈕。其中一個按鈕需要單擊事件處理程序,我希望在指令中處理它,因爲在同一頁面中會有多個此指令的實例。我嘗試了下面的代碼,但無濟於事。Angularjs單擊鏈接中的事件處理

'use strict'; 
angular 
    .module('test-template', []) 
    .directive('testTemplateBricks', [ 
    '$compile', 
    '$timeout', 
     function($compile,$timeout) { 
      return { 
       restrict: 'A', 
       link: function($scope, iElm, iAttrs, controller) { 
        var el = ""; 
        if(iAttrs.needImg=="true") 
        { 
         el += '<input type="file" style="display:none;" class="browse-file"/><button class="btn btn-info" ><span class="glyphicon glyphicon-picture" ng-click="browse()"></span></button>'; 
        } 
        if(iAttrs.needTxt=="true") 
        { 
         el += ' <button class="btn btn-info"><span class="glyphicon glyphicon-pencil"></span></button>'; 
        } 

        $compile(el)($scope); 
        iElm.append(el); 

        $scope.browse = function() { console.log("browsing");}; 

        $timeout(function(){ 
         iElm.on("click",function(e){ 
          console.log("Browsing"); 
          iElm.find("input[type=file]").click(); 
         }); 
        }); 
       } 
      }; 
     } 
    ]); 

編輯http://plnkr.co/edit/bNRLvWjEE7LLvhwRFIae?p=preview

在此示例中,我要的是點擊圖像按鈕時,顯示隱藏的文件瀏覽器。

+0

你對控制檯的任何錯誤?從我的檢查看來,似乎沒有找到輸入,並且'click'方法未定義。 – Dvir

+0

如果你能提供一個工作的plnkr,那將是非常棒的。 –

+0

@Dvir沒有任何錯誤,但$ scope.browse沒有被超時觸發,我得到了console.log,但是每次點擊註冊約100個日誌,第二行輸入類型似乎沒有工作。所以我認爲你是正確的,輸入元素不存在,但它確實顯示在頁面上。 任何解決方案? –

回答

0

所以我不會推薦這種方法來切換元素的可見性,這是​​在模板邏輯中更好地處理的東西。

但是,讓你開始我已經採取了你的代碼,並修改它有點(https://jsbin.com/negawu

angular 
    .module('test-template', []) 
    .directive('testTemplateBricks', [ 
    '$compile', 
    '$timeout', 
     function($compile,$timeout) { 
      return { 
       restrict: 'A', 
       template: '<input type="file" class="browse-file"/>' + 
         '<button class="btn btn-info" ng-show="showImage">' + 
          '<span class="glyphicon glyphicon-picture" ng-click="browse()"></span>' + 
         '</button>' + 
         '<button class="btn btn-info" ng-show="showText">' + 
          '<span class="glyphicon glyphicon-pencil"></span>' + 
         '</button>', 
       link: function($scope, iElm, iAttrs, controller) { 

        $scope.showImage = false; 
        $scope.showText = false; 

        if (iAttrs.needImg == "true") { 
         $scope.showImage = true; 
        } 

        if (iAttrs.needTxt == "true") { 
         $scope.showText = true; 
        } 

        $scope.browse = function() {  
         console.log("browsing"); 
        }; 
       } 
      }; 
     } 
    ]);