2015-06-22 53 views
1

在我的指令中,我有以下代碼,它將用於不斷附加到html元素。AngularJS:在element.append中添加ng-click

//Establishes the type of question and therefore what should be displayed 
app.directive('questionType', function ($http, $compile) { 
    return { 
     restrict: 'A',  
     link: function (scope, element, attr, model) { 

      switch (scope.Question.inputType) { 
       case 'checkbox': 
        //element.append('<input type="checkbox" ng-model="Question.checked"/><button ng-if="input.checked" >X</button>'); 
        break; 
       case 'text': 
        element.append('<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>'); 
        break; 
      } 
     } 
    }; 
}); 

所以當我點擊這個按鈕時,應該調用select屬性函數,這個函數是在附加元素周圍的控制器中。然而它沒有被調用,並且我知道該函數能夠正常工作,因爲如果我將這個按鈕代碼直接放入html頁面,它就可以工作。

我已經看到了使用$編譯爲解決此獲得的一種方式,但是當我使用它只是使我的網頁凍結,並沒有錯誤拿出控制檯。

我嘗試了一些其他的方法,如增加與方法的控制器到我的指令 -

controller: function ($scope, $element) { 
     $scope.selectProperties = function() { 
      aler('test'); 
     } 
    } 

但是這也沒有工作。我需要能夠使用函數調用來更新我的主控制器中的一個對象,所以我不確定我可以這樣做。

任何想法?

回答

5

您應該將compile html綁定到directivesng-click範圍屬性。其他副角度指令不會綁定到範圍屬性。

var strElm = '<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>'; 
var compiledHtml = $compile(strElm); 
element.append(compiledHtml); 

不從指令刪除$compile服務,

和你的代碼應該是這樣的,

//Establishes the type of question and therefore what should be displayed 
 
app.directive('questionType', function($http, $compile) { 
 
    return { 
 
    restrict: 'A', 
 
    link: function(scope, element, attr, model) { 
 

 
     switch (scope.Question.inputType) { 
 
     case 'checkbox': 
 
      //element.append('<input type="checkbox" ng-model="Question.checked"/><button ng-if="input.checked" >X</button>'); 
 
      break; 
 
     case 'text': 
 
      var strElm = '<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>'; 
 
      var compiledHtml = $compile(strElm); 
 
      element.append(compiledHtml); 
 
      break; 
 
     } 
 
    } 
 
    }; 
 
});

+0

嗨這個作品,謝謝!現在唯一的問題(我拿出了我原來的職位的,沒想到卻是相關的)是,如果我試圖從範圍添加的東西到弦,它就會不工作,只會顯示爲未定義 - +範圍。 Question.label +。這會按照我以前的方式工作。 – user3407039

+0

我想你需要在那裏提出一個單獨的問題,通過描述你已經嘗試過的和一些代碼。 :) –

+0

我認爲你是對的。我會接受你的答案,因爲它解決了我所問的問題。從我看到的其他一些示例中使用$ compile的方式略有不同。 – user3407039