指令双向绑定

时间:2015-01-09 05:37:07

标签: javascript angularjs angularjs-directive angularjs-scope

我对AngularJS很新,并试图创建一个添加一些按钮的指令。我试图从指令内部修改控制器范围,但我无法使其工作。这是我的应用程序的示例

app.controller('invoiceManagementController', ['$scope', function ($scope) {
    $scope.gridViewOptions = {
        isFilterShown: false,
        isCompact: false
    };
}]);

app.directive('buttons', function () {
    return {
        restrict: 'A',
        template: '<button type="button" data-button="search" title="Filter"><i class="glyphicon glyphicon-search"></i></button>',
        scope: {
            gridViewOptions: '='
        },
        transclude: true,
        link: function (scope, element, attr, ctrl, transclude) {
            element.find("button[data-button='search']").bind('click', function (evt) {
                // Set the property to the opposite value
                scope.gridViewOptions.isFilterShown = !scope.gridViewOptions.isFilterShown

                transclude(scope.$parent, function (clone, scope) {
                    element.append(clone);
                });
            });
        }
    };
});

我的HTML如下

{{ gridViewOptions.isFilterShown }}
<div data-buttons="buttons" data-grid-view-options="gridViewOptions"></div>

指令内的范围确实发生了变化,但就像是孤立的一样,我确实尝试使用范围属性进行支付并转换,但我可能会遗漏一些东西,会在这里感谢一些亮点

2 个答案:

答案 0 :(得分:0)

当您修改指令的链接功能中的范围时,您正在修改指令的隔离范围(因为这是您已设置的)。要修改父范围,可以将范围分配放在transclude函数中:

transclude(scope.$parent, function (clone, scope) {
    // Set the property to the opposite value
    scope.gridViewOptions.isFilterShown = !scope.gridViewOptions.isFilterShown
    element.append(clone);
});

答案 1 :(得分:0)

好的,终于在今天进行了一些研究后找到了解决方案。不确定是否是最好的解决方案,但现在这种方法非常好。

app.controller('invoiceManagementController', ['$scope', function ($scope) {
    $scope.gridViewOptions = {
        isFilterShown: false,
        isCompact: false
    };
}]);

app.directive('buttons', function () {
    return {
        restrict: 'A',
        template: '<button type="button" data-button="search" data-ng-class="gridViewOptions.isFilterShown ? \'active\' : ''" title="Filter"><i class="glyphicon glyphicon-search"></i></button>',
        scope: {
            gridViewOptions: '='
        },
        link: function (scope, element, attr, ctrl, transclude) {
            element.find("button[data-button='search']").bind('click', function (evt) {
                scope.$apply(function () {
                    // Set the property to the opposite value
                    scope.gridViewOptions.isFilterShown = !scope.gridViewOptions.isFilterShown;
                });
            });
        }
    };
});