2016-01-05 62 views
1

我想获取点击使用指令的参数。我想要获取点击事件中的孩子数据来检查是否有孩子。将参数传递给角度指令点击

.....

HTML

div ng-app="treeApp"> 
<ul> 
    <treeparent></treeparent> 

</ul> 

JS

(function() { 
var treeApp = angular.module('treeApp', []); 
treeApp.directive('treeparent', function() { 
    return { 
     restrict: 'E', 
     template: "<button addchild child='m'>ajith</button><div id='new'></div>" 
    } 
}); 
treeApp.directive('addchild', function ($compile) { 

    return { 
     scope: { 
      'child':'=' 
     }, 
     link: function (scope, element, attrs) { 
      debugger; 
      element.bind("click", function (scope,attrs) { 
       debugger; 

//here i want to get hild ie 'm' 
angular.element(document.getElementById('new')).append("<div><button button class='btn btn-default'>new one</button></div>"); 


       }); 
     } 
    } 

}); 
})(); 

plz帮助我

+1

问题是什么? 'scope.child'不起作用? –

+0

是scode.child未定义 – Ajith

+0

它将是'scope.child'。另外**删除**这个'angular.element(document.getElementById('new'))。append(“

”);' - 直到你在完全错误的方向上走得太远。 – dfsq

回答

1

所以,我觉得scope.childundefined因为它在声明事件中存在重叠。

您可以事件绑定

link: function (scope, element, attrs) { 
     var child = scope.child; 
     element.bind("click", function (scope,attrs) { 

      // here you can use child 
      console.log('child', child); 

     }); 
    } 

或声明参数名不同

link: function ($scope, $element, attrs) { 
     element.bind("click", function (scope,attrs) { 

      // here you can use $scope.child 
      console.log('$scope.child', $scope.child); 

     }); 
    } 

是一个回调有scopeattrs参数之前定义的变量?可能它只有一个$event的说法?

link: function (scope, element, attrs) { 

     element.bind("click", function ($event) { 

      // here you can use child 
      console.log('child', scope.child); 

     }); 
    } 
+0

Anton,对不起,它不是 – Ajith

+0

'bind'的回调只有一个'$ event'参数 –

+0

是从控制器调用指令功能的任何方式 – Ajith

0

用于从指令中父范围呼叫方法

父模板

<test-dir data-method="myFunc"></test-dir> 
<button ng-click="myFunc('world')">click me</button> 

<button test-dir data-method="myFunc" ng-click="myFunc('world')">click me</button> 

指令实施例

.directive('testDir', function() { 
    return { 
     scope: { 
      method: '=', 
     }, 
     controller : function($scope) { 

      $scope.method = function(text) { 
       alert('hello '+text); 
      }; 

     }, 
    }; 
})