[英]pass parameter to angular directive on click
我正在嘗試使用指令獲取有關click的參數。我想在click事件中獲取子數據以檢查是否有子。
.....
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>");
});
}
}
});
})();
請幫我
所以,我認為scope.child
是undefined
的,因為它在聲明事件中是重疊的。
您可以在事件綁定之前定義變量
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);
});
}
回調是否具有scope
和attrs
參數? 可能只有一個$event
參數嗎?
link: function (scope, element, attrs) {
element.bind("click", function ($event) {
// here you can use child
console.log('child', scope.child);
});
}
父作用域中指令的調用方法示例
父模板
<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);
};
},
};
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.