角度指令和控制器

时间:2017-03-02 11:36:20

标签: angularjs

我有一个指令和一个控制器。该指令为休耕:

calcP.directive('modalDialog', function() {
    return {
        restrict: 'E',
        scope: {
            show: '='
        },
        replace: true, 
        transclude: true, 
        link: function(scope, element, attrs) {
            scope.dialogStyle = {};
            if (attrs.width)
                scope.dialogStyle.width = attrs.width;
            if (attrs.height)
                scope.dialogStyle.height = attrs.height;
            **scope.hideModal = function() {
                scope.show = false;
                delete $sope.types.individual;**
            };
        },
        template: "..."
    };
});

我的控制器:

    calcP.controller('calcPCtrl', function($scope, $http, $window, emailSenderEndpoint) {

$scope.getVariantDomovoy = function () {
        $scope.types.domovoy = $scope.variants.domovoy;
    };
    $scope.getVariantIndividual = function () {
        $scope.types.individual = $scope.variants.individual;
    };

    ...
    $scope.modalShown = false;
        $scope.toggleModal = function() {
            $scope.modalShown = !$scope.modalShown;
        };

    });

我的模板:

template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"

我希望通过将某个$ scope添加到函数中来删除它。但浏览器显示错误,它无法找到变量$ scope.types.individual。

我只是尝试自己学习AnangularJS,但仍有一些问题。

1 个答案:

答案 0 :(得分:2)

如果要从指令更改控制器的值,首先必须通过双向绑定将该变量传递给指令。然后您可以更改该值,如下所示。

calcP.directive('modalDialog', function() {
    return {
        restrict: 'E',
        scope: {
            show: '=',
            types: '='
        },
        replace: true, 
        transclude: true, 
        link: function(scope, element, attrs) {
            scope.dialogStyle = {};
            if (attrs.width)
                scope.dialogStyle.width = attrs.width;
            if (attrs.height)
                scope.dialogStyle.height = attrs.height;
            **scope.hideModal = function() {
                scope.show = false;
                scope.types.individual = "";**
            };
        },
        template: "..."
    };
});

确保将$scope.types从控制器传递到指令。与传递show参数

相同

可能是这样的,

<model-dialog show="show" types="types"></model-dialog>