は、最新の要件に照らして回答
を更新:
私は コントローラからの指令機能(すなわちupdateMap)を呼び出すようにしようとしています。
あなたはコントローラと孤立ディレクティブの間で変数を共有するServiceを使用することができます。以下の例では、サービスは実行される機能を保持しています。クリックされた各ディレクティブは、自身のupdateMap()
機能にサービスの機能を設定します。次にコントローラonFolderPathClicked()
は、以前に設定された機能を実行するサービスexecuteFunction()
を呼び出します。
script.js:
var module = angular.module('testApp', []);
module.service('updateMapService', function(){
var updateMapFunction = null;
this.executeFunction = function(){
updateMapFunction();
};
this.setFunction = function(fn){
updateMapFunction = fn;
};
});
module.controller('crtl', function($scope, updateMapService) {
$scope.onFolderPathClicked = function(){
updateMapService.executeFunction();
};
});
module.directive('folder', function($compile) {
return {
restrict: 'E',
scope: {
id: '@',
folderPath: "="
},
template: '<p ng-click="onFolderClicked()">{{id}}</p>',
controller: function($scope, $element, updateMapService) {
$scope.onFolderClicked = function(){
updateMapService.setFunction(updateMap);
addFolder();
};
var addFolder = function() {
$scope.folderPath = $scope.id + ":click here for calling update map";
var el = $compile('<folder id="n" folder-path="folderPath"></folder>')($scope);
$element.parent().append(el);
};
var updateMap = function() {
alert('inside updateMap()..' + $scope.id);
}
}
}
});
のindex.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="testApp" ng-controller="crtl">
<div>FolderPath : <a ng-click="onFolderPathClicked()">{{ folderPath }}</a> </div>
<folder id="1" folder-path="folderPath"></folder>
<folder id="2" folder-path="folderPath"></folder>
</div>
</html>
また、属性としてそれを渡してから保存するようにサービスにfolder-path
を移動することができます。コードはそれを属性として渡すということは、サービスでは2回行うことを意味しますが、サービスではそれを設定して1回取得(コードの再利用)を意味します。
ありがとうマッチMatthew :)私はもう一つ疑いがある。私はコントローラから指示関数(つまり、updateMap)を呼び出そうとしています。私はディレクティブごとにスコープを取得することができません。私のプランナーを見てください。[CallingControllerFnFromDirective](https://plnkr.co/edit/xPp650yO6eWZWwxvKPj3?p=preview)私はコントローラーの指示機能からのクリック機能を扱うことができます(「更新マップを呼び出すにはここをクリックしてください」というテキストをクリックするたびに警告が表示されます)が、指示の正しい範囲は渡されません。常にIDを2と表示しています。これで助けてください。 –
@BharatSewani最新の要件に照らして私の答えを更新しました。 –