简体   繁体   中英

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

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.

Each directive has an isolated scope.

That means that the 'addNew' function is not available in the scope the directives template is in.

To accomplish this you can add the following line to the 'scope' property of your directive definition:

addNew: '&'

This will bind the scope property to the one of original scope (see: 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: '&'
} 
...........
}}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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