从父控制器访问指令的属性

时间:2013-12-20 19:00:24

标签: javascript angularjs angularjs-directive

我有一个datetime指令,其范围包含两个属性:datetime。如何从父控制器访问这些属性?我试过这个

<div id="inputs" ng-controller="InputCtrl">
    Start: <datetime ng-model="start"></datetime>
    End: <datetime ng-model="end"></datetime>

    You have chosen to start on {{start.date}}, {{start.time}} 
    and end on {{end.date}}, {{end.time}}.
</div>

更改输入时,未填充start.datestart.timeend.dateend.time的值。如何从父控制器访问指令范围?

这是我的指令代码:

angular.module("components", [])
    .directive("datetime", function () {
        return {
            restrict: 'E',
            scope: {},
            controller: function ($scope) {
                $scope.time = "12:00 PM";
                $scope.date = "12/01/2013";
            },
            template: 
                '<div><div class="control-group input-append">' +
                '<input class="input-small" type="text" ng-model="date" data-date-format="mm/dd/yyyy" bs-datepicker>' +
                '<button type="button" class="btn" data-toggle="datepicker"><i class="icon-calendar"></i></button>' +
                '</div>' +
                '<div class="control-group input-append">' +
                '<input type="text" class="input-small" ng-model="time" bs-timepicker>' +
                '<button type="button" class="btn" data-toggle="timepicker"><i class="icon-time"></i></button>' +
                '</div></div>',
            replace: true
        };
    });

1 个答案:

答案 0 :(得分:2)

您应该将指令范围变量绑定到指令属性,如下所示:

angular.module("components", [])
    .directive("datetime", function () {
        return {
            restrict: 'E',
            scope: {
                model: "=ngModel"
            },
            controller: function ($scope) {
                $scope.model.time = "12:00 PM";
                $scope.model.date = "12/01/2013";
            },
            template: 
                '<div><div class="control-group input-append">' +
                '<input class="input-small" type="text" ng-model="date" data-date-format="mm/dd/yyyy" bs-datepicker>' +
                '<button type="button" class="btn" data-toggle="datepicker"><i class="icon-calendar"></i></button>' +
                '</div>' +
                '<div class="control-group input-append">' +
                '<input type="text" class="input-small" ng-model="time" bs-timepicker>' +
                '<button type="button" class="btn" data-toggle="timepicker"><i class="icon-time"></i></button>' +
                '</div></div>',
            replace: true
        };
    });

"=ngModel"表示您将隔离范围中的model绑定到父范围中ng-model中的变量。