另一个指令中的指令 - 范围var undefined

时间:2016-04-12 11:39:50

标签: angularjs angularjs-directive angularjs-scope smart-table

我正在尝试从我定义的自定义指令中生成一个智能表指令:

<div ng-controller="myContrtoller">
  <containing-directive></containing-directive>
</div>

指令定义:

angular.module('app')
.directive('containingDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<table st-table="collection" st-pipe="scopeFun"></table>', 
        link: function(scope, elem, attrs) {
            scope.scopeFun = function () {
                // solve the misteries of life
            }
        }
    }
});

正如您所看到的,我的指令尝试用st-table指令生成的模板替换元素,使用st-pipe指令取决于第一个,简要说明:

ng.module('smart-table')
  .controller('stTableController' function () {
      // body...
  })
  .directive('stTable', function () {
    return {
      restrict: 'A',
      controller: 'stTableController',
      link: function (scope, element, attr, ctrl) {
        // body
      }
    };
  })
  .directive('stPipe', function (config, $timeout) {
    return {
      require: 'stTable',
      scope: {
        stPipe: '='
      },
      link: {

        pre: function (scope, element, attrs, ctrl) {
          var pipePromise = null;
          if (ng.isFunction(scope.stPipe)) { // THIS IS ALWAYS UNDEFINED
            // DO THINGS
          }
        },

        post: function (scope, element, attrs, ctrl) {
          ctrl.pipe();
        }
      }
    };
  });

问题:
st-pipe指令检查范围var stPipe是否由if (ng.isFunction(scope.stPipe))定义。结果总是未定义。通过检查我发现了两件事:

  1. stPipe指令中,我scope.stPipescopeFun定义的containingDirective值应为undefined scope scope.$parent } object但在$scope.scopeFun对象中已定义
  2. 如果我在myContrtoller中定义replace: false我没有任何问题,那么一切正常。
  3. 解决方案:
    我确实找到了解决方案,但我不知道到底发生了什么:

    1. containingDirective
    2. 中设置scope.scopeFun
    3. containingDirective
    4. 预链接功能中定义scopeFun

      问题:

      1. 如果在控制器中定义了stPipe指令scope对象中的scope.$parent,为什么containingDirective可用 public double GetTotalSalary(int empId, double empSalary) { return context.Employees.Where(e=>(e.Id==empId && e.Sl==empSalary)).Sum(e=>e.Salary); } ,如果在{{1}中定义的话}}?
      2. 我的解决方案究竟发生了什么,是否有可能找到更清洁的解决方案?

1 个答案:

答案 0 :(得分:0)

docs:“替换过程将所有属性/类从旧元素迁移到新元素”所以发生了这样的事情:

<containing-directive whatever-attribute=whatever></containing-directive>

正在被替换为

<table st-table="collection" st-pipe="scopeFun" whatever-attribute=whatever></table>

并且某种方式st-table没有享受额外的属性(即使根本没有属性......) 通过将containingDirective指令模板包装在另一个div中修复了问题(我现在可以使用replace:true):

<div><table st-table="collection" st-pipe="scopeFun"></table></div>

如果某人有更有条理的答案,我们将非常感激