如何以嵌套方式将预定义指令(ng-click)与自定义指令一起使用

How do I use predefined directives (ng-click) with custom directives in a nested fashion?

本文关键字:指令 自定义 一起 ng-click 嵌套 方式 预定义      更新时间:2023-09-26

如何单击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>

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

附言:我也不知道你是否感兴趣,但如果你想抽象掉jquery插件,有一个select2包装器指令。angular ui select2