如何以嵌套方式使用预定义指令(ng-click)和自定义指令?

时间:2014-09-16 20:09:15

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-click

如何点击ngSearchBar.html中的按钮?我想使用与我的父指令(ngSearchBar.html)相同的范围作为我的子指令(ng-click),这样我就可以做scope.search = function(){};在我的父指令中。

myAppControllers.constant('baseDomainConstant', 'http://127.0.0.1:5000/v1/');

myAppControllers.factory('technologiesFactory', ['$resource', 'baseDomainConstant', function($resource, baseDomainConstant) {
    return $resource(baseDomainConstant + 'technologies.json', {}, null);
}]);

myAppControllers.directive('ngSearchBar', ['technologiesFactory', function(technologiesFactory) {
return {
    restrict: 'A',
    templateUrl: "partials/ngSearchBar.html",
    replace: true,
    scope: false,
    link: function (scope, element, attributes) {
        var data = '';

        scope.search = function() {
            console.log('TESTING');
        };

        element.find('#search').on('click', function() {
            alert(JSON.stringify($('.select2').select2('data')));
        });

        technologiesFactory.get().$promise.then(function(result) {
            _.forEach(result.data, function(technologyNames, category) {
                data += '<optgroup label="' + category + '">';
                _.forEach(technologyNames, function(technology) {
                    data += '<option value="' + technology.technology_id + '">' + technology.webname + '</option>';
                });
                data += '</optgroup>';
            });

            element.find('#multi-append').append(data);
            $('.select2').select2('enable', true);

        });
    },
    controller: ['$scope', function($scope) {
        $('.select2').select2({ placeholder: 'Search' });
        $('.select2').select2('enable', false);

        $scope.search = function() {
            console.log('TESTING');
        };

    }]
};
}]);

myAppControllers.controller('ViewCtrlv2', ['$scope', function($scope) {
        $scope.search = function() { console.log('Testing'); };
    }]
);

这是partials / ngSearchBar.html“

<div class="control-group">
<div class="controls">
    <div class="input-append">
        <select id="multi-append" class="select2" multiple="multiple" style="width:400px;"></select>
        <button class="btn" type="button" ng-click="search()">
            <i class="icon-search"></i>
        </button>
    </div>
</div>

我正在使用我的指令。 HTML。

<div class="wrapper dashboard inc-footer">

<div ng-include="'partials/header.html'"></div>

<span data-ng-search-bar></span>

<div class="sticky-footer" ng-include="'partials/footer.html'"></div>

</div>

1 个答案:

答案 0 :(得分:1)

模板中的

ng-click应该可以正常工作。如果希望指令共享父作用域,则应将scope: false放在指令定义对象上。

P.S。另外,如果你想抽象出jquery插件,我也不知道你是否感兴趣但是有一个select2包装器指令。 angular ui select2