如何动态地将指令附加到angularjs中的div

时间:2015-10-07 08:42:49

标签: javascript angularjs

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 ng-app = "myApp" ng-controller = "someController">

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

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

</div>

不使用Jquery是否有任何好的Angular方法将指令(testInput)附加到#container? 见下面的jsfiddle链接 http://jsfiddle.net/4L6qbpoy/1/

1 个答案:

答案 0 :(得分:0)

更多Angular方法是在控制器中使用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>