单击时将参数传递给angular指令

时间:2016-01-05 11:17:20

标签: javascript jquery angularjs

我正在尝试使用指令获取点击参数。我想在点击事件中获取子数据以便检查是否有孩子。

.....

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>");


                 });
        }
    }

});
})();

请帮帮我

2 个答案:

答案 0 :(得分: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);

        });
    }

答案 1 :(得分: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);
            };

        },
    };
})