如何从控制器中的指令调用函数? AngularJS

时间:2016-11-26 16:20:52

标签: angularjs directive

如何在控制器中从指令调用函数clearCopy

这是我的html的一部分:

<tr ng-form="mForm" my-directive>
  <td>
    <div>
      <button class="btn btn-default" ng-click="saveData(row)"> </button>
    </div>
  </td>
</tr>

这是我的指示:

angular.module("w.forms").directive("myDirective", function () {
    return {
        require: ["^form"],
        link: function (scope, element, attrs, ctrls) {
            scope.$watch(function () {
            // ...... something
            }, true);

            scope.clearCopy = function () {
                // do something
            }
        }
    };
});

这是我的控制器:

angular.module("app").controller("datalesController", function ($scope) {
  $scope.saveData(row) = function {
     // do something then run function from directive
     // till this part everything works fine
    $scope.clearCopy()   // unfortunately it doesn't work :(
  }
}

一切正常,但控制器中的函数$scope.clearCopy()不起作用。

1 个答案:

答案 0 :(得分:-2)

  

HTML

<html>
<script src="library/angular.min.js"></script>
<script src="practice.js"></script>
<head>
</head>
<body ng-app="app" ng-controller="datalesController">
    <div my-directive>
      <button ng-click="saveData()">press </button>
    </div>
</body>
</html>
  

控制器

angular.module('app',[]).controller("datalesController", function ($scope) {
  $scope.saveData = function() {
     // do something then run function from directive
     // till this part everything works fine
    $scope.clearCopy(); // unfortunately it doesn't work :(
  };
});
  

指令

angular.module('app',[]).directive("myDirective" , function () {
    return {
        restrict:'A',
        link: function (scope, element, attrs, ctrls) { 
           scope.clearCopy = function () {
                console.log("calling from controller");
            };
        }
    };
});
  

我更改了运行请求的代码