【问题标题】:Angular call controller function from nested custom directive来自嵌套自定义指令的角度调用控制器功能
【发布时间】:2017-07-01 15:42:34
【问题描述】:

我需要一些帮助。 我有一个控制器,其中包含一个名为“loadInformation()”的函数。在这个控制器内部,我使用了一个使用自定义指令进行 DOM 操作的服务。 这些是指令:

第一个自定义指令:

angular.module('...').directive('ngInputString', function () {
return {
restrict: 'AE',
replace: 'true',
scope: {
  savedInformation: '=',
  type: '@',
  values: '='
},
templateUrl: 'directives/templates/inputString.html',
link: function (scope, element, attrs) {
  scope.filterOb = {ttype: scope.type};
}
}
});

HTML 文件:

<div>
<input ttype="{{type}}" type="text" placeholder="{{param.name}}"         value='{{param.value}}'
     class='clean-input form-control'/>
 <ng-saved-information type="STRING" saved-information="savedInformation"></ng-saved-information>
 </div>

嵌套自定义指令:

angular.module('semtrosApp').directive('ngSavedInformation', function    () {
return {
restrict: 'AE',
replace: 'true',
scope: {
  savedInformation: '=',
  type: '@'
},
template: '<ul><li ng-repeat="information in savedInformation |    filter:filterOb">{{information.value}}<button type="button" ng-click="..?..">Use Information</button></li></ul>',
link: function (scope, elem, attrs) {
  scope.filterOb = {ttype: scope.type};
}
}
});

当我不使用嵌套指令时,它可以很好地处理那段代码:

elem.bind('click', function() {
    scope.$apply(function() {
      scope.loadInformation();
    });
  });

但是当它们嵌套时,第二个自定义指令只是在父指令的范围内查看。知道如何通过函数调用吗?

【问题讨论】:

  • 我很惊讶嵌套的自定义指令可以调用scope.loadInformation() 并在父指令中找到它。两个指令都具有隔离作用域——它们根本不应该看到它们的父作用域。

标签: javascript angularjs


【解决方案1】:

看起来ngInputString 指令已经接收了一些数据并将其传递给ngSavedInformation。为什么不让它也接受loadInformation 回调并将其传递下去?

angular.module('...').directive('ngInputString', function () {
  return {
    scope: {
      savedInformation: '=',
      type: '@',
      values: '=',
      loadInformation: '&'
    },
    // etc
  }
});

 <ng-saved-information type="STRING" saved-information="savedInformation" load-information="loadInformation()"></ng-saved-information>

 angular.module('semtrosApp').directive('ngSavedInformation', function () {
   return {
     scope: {
       savedInformation: '=',
       type: '@',
       loadInformation: '&'
     },
     // etc
   }
 });

此外,您可以在模板中执行以下操作,而不是手动创建点击处理程序:

ng-click="loadInformation()"

【讨论】:

  • 用“&”符号共享函数的可能性正是我所寻找的!非常感谢!
  • 最后一个问题:是否可以将任何参数传递给父控制器中的函数? &lt;li ng-repeat="information in savedInformation | filter:filterOb"&gt;{{information.value}}&lt;button type="button" ng-click="loadInformation(information)"&gt; 似乎不起作用。
  • 向父函数commander.loadInformation(message) 添加一个值是第一步,ng-click="loadInformation({message:3})" 作用于第一个指令。但是如何传递给嵌套的呢?自定义指令不是很直观..
  • @Chris 看起来应该可以。如果您在 plnkr 中创建该问题的实时示例,我可以提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多