繁体   English   中英

动态创建元素的AngularJs调用控制器功能

[英]AngularJs call controller function from dynamically created element

我有一个控制器,并希望创建动态元素。当我创建它时,该元素应调用controller函数,但不调用该函数

app.controller('AbnTestController', ['$scope','$timeout',function($scope,$timeout) {
 ..........................
var tree1;
tree1 = [
  {
    label: 'test1',
    id:'1',
    type:'t',

  }];
  return $scope.addnew= function() {
  .........
   something

};

在我的指令中,我创建了动态元素;

app.directive('mytree', [
'$timeout', function($timeout) {
  return {
    restrict: 'E',
    controller: function($scope) {
      $scope.launch = function (mn) {........something.....}},

     template: "<a ng-click='addnew()'>Click</a>",
    replace: true,
    scope: {
      treeData: '=',
      onSelect: '&',    
      initialSelection: '@',
      treeControl: '='
    } 
    ...........
    }}]);

我想从动态创建的元素中调用“ addnew”函数。

每个指令都有一个隔离的范围。

这意味着指令模板所在的范围中'addNew'函数不可用。

为此,您可以将以下行添加到指令定义的'scope'属性中:

addNew: '&'

这会将scope属性绑定到原始范围之一(请参阅: https : //docs.angularjs.org/guide/directive

您的指令应如下所示:

app.directive('mytree', [
 '$timeout', function($timeout) {
  return {
restrict: 'E',
controller: function($scope) {
  $scope.launch = function (mn) {........something.....}},

 template: "<a ng-click='addnew()'>Click</a>",
replace: true,
scope: {
  treeData: '=',
  onSelect: '&',    
  initialSelection: '@',
  treeControl: '=',
  addNew: '&'
} 
...........
}}]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM