如何将数据从指令传递给控制器​​?

时间:2015-07-06 10:54:17

标签: angularjs

我目前正致力于在我的角度应用程序中集成插件,并且我试图将其转换为指令。我已经摆弄了插件的事件和方法但未能获得理想的结果。这是我的代码:

HTML

<div class="input-daterange datepicker full" rangepicker ng-model="packer.selected.date">
    <i class="fa fa-calendar"></i>
    <div class="inputs datepicker">
        <input 
            ng-model="packer.selected.date.start"
           name="start" 
           value="<% packer.initData.dateStart %>">
        <span class="add-on">-</span>
        <input 
            ng-model="packer.selected.date.end"
           name="end" 
           value="<% packer.initData.dateStart %>">
    </div>
</div>

Javascript:

Application.directive('rangepicker', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, ngModel) {

            $(element).datepicker({
                format: 'yyyy-mm-dd'
            });

            $(element).on('changeDate', function(){
                /*
                $(element).find('input').each(function(){
                    $(this).trigger('input');

                }) */                
            })

        }
    };
});

Application.controller('PackingStatisticsController', ['$scope', '$http', 'initData', function($scope, $http, initData) {

    var packer = this;
    packer.initData = initData;

    packer.selected = {
        date : {
            start : "",
            end : ""
        },
        user : ""
    }

    packer.log = function()
    {
        console.log(packer.selected);
    }


}]);

我读过任何我认为与我的问题相关的内容,但我还没有设法摆脱混乱的面纱。注释代码应该触发输入值更改事件,我希望更新模型。我无法理解我在html中指定的模型在哪里符合我的指令数据。

https://bootstrap-datepicker.readthedocs.org/en/latest/index.html这是我正在使用的插件。

2 个答案:

答案 0 :(得分:1)

你可以从控制器的范围作为属性传递你想要修改的模型,如下所示(查看范围属性):

Application.directive('rangepicker', function() {
return {
    restrict: 'A',
    scope : {
       model : '='
    }
    link: function(scope, element, attrs, ngModel) {

        $(element).datepicker({
            format: 'yyyy-mm-dd'
        });

        $(element).on('changeDate', function(){
            /*
            $(element).find('input').each(function(){
                $(this).trigger('input');

            }) */                
        })

    }
};
});

并在html中:

<div class="input-daterange datepicker full" model="myModelVar" rangepicker ng-model="packer.selected.date">

现在myModeVar是双向数据可绑定的。一旦你在指令中更改它,它就会在控制器的范围内发生变化。

在控制器中:

Application.controller('PackingStatisticsController', ['$scope', '$http', 'initData', function($scope, $http, initData) {
    $scope.myModelVar = ...;
}]);

答案 1 :(得分:1)

唉,我已经做到了!

new