angular $ watch未触发,但模型在指令模板中更新

时间:2013-08-13 12:37:46

标签: javascript angularjs angularjs-directive

我无法在Angular中捕获模型的更改事件。一切正常,我可以在模板中查看更新的模型值,但在控制器中不可用。

这是我的代码: 控制器:

//watches the date selector
    $scope.$watch('startDate', function (value1, value2) {
        console.log (value1, value2);
    });

模板:

{{startDate}}{{endDate}}
<daterangepicker readonly start="startDate" end="endDate" format="currentUser.settings.dateFormat" options="daterangeoptions"></daterangepicker>

指令:

//daterange picker
myAppDirectives
.directive('daterangepicker', function ($parse, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            options: '=options',
            start: '=start',
            end: '=end',
            format: '=format'
        },
        compile: function (element, attrs){
            //debugger;
            //var initialVal = attrs.startDate + attrs.endDate;
            var htmlText = '<div class="input-append pull-right">';
            htmlText += '<input type="text" readonly="" id="range" value="" />';
            htmlText += '<input type="hidden" name="startDate" ng-model="startDate" value="" />';
            htmlText += '<input type="hidden" name="endDate" ng-model="endDate" value="" />';
            htmlText += '<span class="add-on"><i class="icon-calendar"></i></span></div>';
            element.replaceWith(htmlText);
            //return function, does all the logic
            return function (scope, element, attrs) {
                var daterangecallback = function (start, end) {
                    //let angular know change happened to $scope
                    scope.start = start;
                    scope.end = end;
                    scope.$apply();
                }
                $timeout(function(){ 
                    var range = element.find('#range');
                    range.daterangepicker (scope.options, daterangecallback);
                    range.val(moment(scope.options.startDate).format(scope.options.format) + ' - ' + moment(scope.options.endDate).format(scope.options.format));
                });
            }
        }
    }
})

0 个答案:

没有答案