如何从AngularJS中的另一个指令调用指令?

时间:2014-04-15 11:45:20

标签: angularjs angularjs-directive angularjs-scope

我刚开始使用AngularJS。有没有办法使用另一个指令的指令? 我想在点击父级时添加新的<div time></div>

编辑: index.html

<div class="time" addtime ng-click="addTime()">
  <!-- ADD NEW <div resizable draggable ...></div> from directive 'time' HERE -->
</div>

编辑: directive.js

dragDirectives.directive('addtime', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attr, ctrl) {

    },
    controller: function addtimeCtrl($scope, $element){
      $scope.addTime = function() {
        // ADD NEW <div resizable draggable ...></div> from directive 'time'
      };
    }
  }
});

dragDirectives.directive('time', function() {
  return {
    restrict: 'A',
    template: '<div resizable draggable class="duree" ng-class="{\'resize-active\': isResizeActive, \'drag-active\': isDragActive }" ng-style="{ width: myWidth, left: myLeft }">',
    link: function(scope, element, attr) {

    }
  }
});

2 个答案:

答案 0 :(得分:1)

使用Angular,你不会做与DOM相关或jQuery-ish的东西(即addEventListener)。方法是:

  • 让模型描述您拥有的<div time>元素,例如:

    scope.timeElements = [];
    
  • 在模板中对它进行反对:

    <div time ng-repeat="t in timeElements"></div>
    
  • 通过操纵模型来处理事件,例如:

    (HTML)

    <div class="time" addtime ng-click="addTime()">
    

    (JS)

    scope.addTime = function() {
        scope.timeElements.push(something);
    };
    

这只是一个真正解决方案的大纲,因为许多细节仍然缺失,但你应该明白这一点。一个小提琴将有助于更具体。

另请查看this

答案 1 :(得分:1)

require: '^parent' // a better way to go

dragDirectives.directive('addtime', function() {
  return {
    restrict: 'A',
    template: '<div time ng-repeat="t in timeElements"></div>',
    link: function(scope, element, attr, ctrl) {
      scope.timeElements = [1, 2, 3]
    },
    controller: function addtimeCtrl($scope) {
      this.addTime = function() {
        $scope.timeElements.push($scope.timeElements.length + 1);
      };
    }

  }
});

dragDirectives.directive('time', function() {
  return {
    restrict: 'A',
    require: '^addtime',
    template: '<div ng-click="addTime()">time</div>',
    link: function(scope, element, attr, ctrl) {
      scope.addTime = ctrl.addTime;
    }
  }
});