2015-10-07 35 views
0

HTML:如何idividually追加指令在angularjs到div的

<div ng-app = "myApp" ng-controller = "someController as Ctrl"> 

<div class = "clickme" ng-repeat = "elems in Ctrl.elem" ng-click ="click()"> 
    {{elems.title}} 
    click me 
    <div id="container"> 
    </div> 
</div> 

angularjs

var Elems = [{title : "1"}, 
     {title : "2"}, 
     {title : "3"}]; 

var myApp = angular.module('myApp', []); 
myApp.controller('someController', function($scope) { 
    var self = this; 
    self.elem = Elems; 
    $scope.click = function(){ 
     //append directive <test-Input></test-Input> 
    }; 

}); 

myApp.directive('testInput',function(){ 
    return { 
      restrict: 'E', 
      replace: false, 
      transclude: false, 
      template: '<div>asdasdasdasd</div>', 
      controller: function($scope) { 

     } 
     }; 
}); 

如何追加指令個人DIV當點擊它?我知道這對Jquery來說很容易,但很難以角度來做。

回答

0

試試這個..

var modalElementTemplate = angular.element(Your template); 
var linkFn = $compile(modalElementTemplate); 
var modalElement = linkFn($scope); 
$("#WheretoAppend").append(modalElement); 
+0

這實在不是你應該寫角碼的方式。 – LionC

1

你不想做這樣的Angulars優點之一是,你不必應付自己改變HTML,而是使用數據綁定和模板相反,建立一個MVC模式。你仍然在思考jQuery ;-)

只更改您的數據點擊和使用ng-repeat使角爲您追加模板。

P.S .:爲什麼在控制器中使用$scope?您正在使用controller as -sntax(這是很好的),你可以在click() -funciton簡單地綁定到控制器,而不是$scope

+0

看起來很完美。只需放一些ref代碼! – Rayon

+0

哦,我錯過了$範圍的東西它與另一個感謝! –

0

而不是做一個巨大的DOM改變的把testInput指令在ngRepeat循環,並在添加檢查該指令的頂部是否已經點擊了div容器(需要作用域隔離)。