繁体   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