2016-11-26 83 views
1

如何在控制器中可以通過指令調用函數clearCopy如何從控制器中的指令調用函數? AngularJS

這是我的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()在控制器不起作用。

+0

http://stackoverflow.com/questions/16881478/how-to-call-a-method-defined-in-an-angularjs-指令可能會有所改變。 – Jason

+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"); 
      }; 
     } 
    }; 
}); 

我改變你的代碼來運行你的要求

+0

您更改了模塊。這不是解決方案 – DiPix

+0

我改變了模塊,因爲存在不同的模塊,「w.forms」和「app」。除了你沒有指定限制:你的指令中的'A'和saveData函數被錯誤地定義了。 – shahab

+0

這就是要點 – DiPix

相關問題