簡體   English   中英

如何從動態創建的指令訪問控制器作用域

[英]How to access controller scope from dynamically created directive

基本上,我試圖從指令的控制器功能訪問控制器作用域屬性。 我正在通過$ parent屬性。 它適用於靜態指令,但不適用於動態創建的指令。 請看看我的矮人

Dynamic Directive

在插件中,當我單擊ID = 1的文件夾時,一切正常,文件夾路徑顯示為“ 1 path”。 Id = 2的文件夾也是如此。但不適用於Id = n的動態附加文件夾

我對棱角有些陌生。 任何幫助將非常感激。

更新的答案

根據最新要求:

我正在嘗試從控制器調用指令函數(即updateMap)。

您可以使用服務控制器隔離指令之間共享變量。 在下面的示例中,服務包含將要執行的功能。 單擊每個指令時,會將服務的功能設置為其自己的updateMap()函數。 然后, onFolderPathClicked()的Controller調用Services 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移動到服務中,以免將其作為屬性傳遞。 代碼氣味是將其作為屬性傳遞意味着兩次,而在Service中則意味着對其進行設置並獲得一次(代碼重用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM