2015-10-07 83 views
1
var myApp = angular.module('myApp', []); 

myApp.controller('someController', function($scope) { 
    $scope.click = function(){ 
     alert("asd"); 
    }; 

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

     } 
     }; 
}); 

HTML DIV:如何动态追加指令在angularjs

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

    <div class = "clickme" ng-click ="click()"> 
     click me 
    </div> 

    <div id="container"> 
    </div> 

</div> 

不使用jQuery是有附加指令(testInput)到#container的任何好办法角? 见下面的jsfiddle链路 http://jsfiddle.net/4L6qbpoy/1/

回答

0

更多角的方法是在控制器以使用ngIf/ngShow一些标志:

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

 
myApp.controller('someController', function($scope) { 
 
    $scope.click = function() { 
 
     $scope.test = true; 
 
    }; 
 
}); 
 

 
myApp.directive('testInput', function() { 
 
    return { 
 
     restrict: 'E', 
 
     replace: false, 
 
     transclude: false, 
 
     template: '<div>asdasdasdasd</div>', 
 
     controller: function($scope) {} 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> 
 

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

 
    <div class="clickme" ng-click="click()">click me</div> 
 

 
    <div id="container"> 
 
     <test-input ng-if="test"></test-input> 
 
    </div> 
 

 
</div>