简体   繁体   English

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

[英]AngularJs call controller function from dynamically created element

i have one controller and want to create dymanically element.When i create it the element should call the controller function ,but the function is not called 我有一个控制器,并希望创建动态元素。当我创建它时,该元素应调用controller函数,但不调用该函数

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

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

};

In my directive ,i create dynamic element; 在我的指令中,我创建了动态元素;

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: '='
    } 
    ...........
    }}]);

I want to call 'addnew' function from dynamically created element. 我想从动态创建的元素中调用“ addnew”函数。

Each directive has an isolated scope. 每个指令都有一个隔离的范围。

That means that the 'addNew' function is not available in the scope the directives template is in. 这意味着指令模板所在的范围中'addNew'函数不可用。

To accomplish this you can add the following line to the 'scope' property of your directive definition: 为此,您可以将以下行添加到指令定义的'scope'属性中:

addNew: '&'

This will bind the scope property to the one of original scope (see: https://docs.angularjs.org/guide/directive ) 这会将scope属性绑定到原始范围之一(请参阅: https : //docs.angularjs.org/guide/directive

Your directive should look like this: 您的指令应如下所示:

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