如何从动态创建的指令访问控制器范围

时间:2017-01-20 18:01:16

标签: javascript angularjs

基本上我试图从指令的控制器功能访问控制器范围属性。我是通过$ parent属性来做的。它适用于静态指令,但不适用于动态创建的指令。 请看看我的plunker

Dynamic Directive

在一个plunker中,当我点击Id = 1的文件夹时,一切顺利,文件夹路径显示为“1路径”。 Id = 2的文件夹也是如此。 但它对于Id = n

的动态附加文件夹不起作用

我对角度有些新意。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

更新了答案

根据最新要求:

  

我试图从中调用指令函数(即updateMap)   控制器。

您可以使用 Service 控制器隔离指令之间共享变量。在下面的示例中,服务保存将要执行的功能。单击每个指令会将Service的功能设置为它自己的updateMap()功能。然后onFolderPathClicked()中的Controller调用服务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移动到服务中,以便将其作为属性传递保存。代码味道是将其作为属性传递意味着这样做两次,而在服务中它意味着设置它并获得它一次(代码重用)。

相关问题