javascript - 如何根据指令中的属性设置添加附加功能?

标签 javascript angularjs angularjs-directive controller

我正在为我的 Angular 应用程序创建一个具有基本功能的自定义指令。除了该指令之外,我还想添加一个类似于附加设置选项的属性,以便在提到属性时我可以添加扩展功能。

我想做这样的事情:

 <div use-date-picker this-ngmodel="formData.dt" today></div>

在上面的自定义指令中,我希望日期选择器输入字段仅在添加 today 属性时才具有今天的日期。现在,我不知道如何在该指令中定义该函数,因此仅当“today”属性添加到调用该指令的 DIV 时,它才会添加默认的今天日期。我尝试了这个,但它不起作用:

app.directive('useDatePicker', function() { 

    return {
        restrict: 'A',
        replace:true,
        scope: {
            thisNgmodel: '='            
        },
        template: '<div class="input-group">' +         
                    '<input type="text" class="form-control" readonly="readonly" name="dt" ng-model="thisNgmodel" datepicker-popup="{{format}}" is-open="datepickers.dt" datepicker-options="dateOptions" ng-required="true" close-text="Close" />' +
                  '</div>   ',        

        link: function(scope, element, attr) {
            console.log(scope.thisNgmodel);
            console.debug(scope);

            // Here I am trying to add the default Today's date if today attribute is added
            if (element.attr('today')) {
                $scope.today();
            }
        },

        controller: function($scope) {
                //DatePicker
                  $scope.today = function() {
                    $scope.thisNgmodel = new Date();
                  };


                // ....... etc.. etc.. with other controller settings .......
            }

    };
});

如果提到属性,我可以向指令模板添加额外的函数吗?上面的代码我做错了什么?

最佳答案

指令的

controller属性与module.controller不同。它的主要目的是与其他指令的 api 进行通信...引用自 angularjs 文档

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link

您可以在链接功能中将模型的值设置为新日期...

if (element.attr('today')) {
   scope.thisNgmodel = new Date();
}

关于javascript - 如何根据指令中的属性设置添加附加功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554407/

相关文章:

angularjs - 以编程方式插入指令 AngularJS

javascript - AngularJs TypeError : $scope. posts.push 不是一个函数

javascript - angularjs ngRepeat 指令不触发列表中其他项目的摘要

angularjs - 防止异步唯一验证器仅在编辑时验证相同的值?

javascript - 如何在 Meteor javascript 中使用 Mongodb 填充下拉菜单?

javascript - angular-ui-bootstrap:展开后禁用组标题

对象数组中的javascript排序元素

javascript - angular.js 防止空数

javascript - 同一页面中的多个基本滑动切换不起作用

javascript - 如何使用 underscore.js 找到 javascript 数组中存在的给定值?