按钮在angularjs指令中不起作用

Button inside angularjs directive does not work

本文关键字:不起作用 指令 angularjs 按钮      更新时间:2023-09-26

我在一个页面中使用了两次指令。在指令内部,我放置了一个按钮,点击删除第一个指令并显示另一个。但即使在ng-click函数启动时,这些值也不会改变。我做错了什么?这是我的HTML代码。

<body ng-controller="mainCtrl">
<new-directive ng-show="firstDirective" passvar="first passing value"></new-directive>
<new-directive ng-show="secondDirective" passvar="second passing value"></new-directive>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>

test.html文件:
{{content}}, {{passvar}} <button ng-click="otherOne()">show other directive</button>
JS文件:
app.controller('mainCtrl', function($scope){
$scope.firstDirective = true;
});
app.directive('newDirective',function(){
// Runs during compile
return {
    restrict: 'E',
    templateUrl: 'test.html',
    scope: {
        passvar: '@'
    },
    controller: function ($scope) {
        $scope.content= 'Random Content';
        $scope.firstDirective = true;
        $scope.firstDirective = false;
        $scope.otherOne = function(){
            $scope.firstDirective = false;
            $scope.secondDirective = true;
        }
    }
};
});

即使是为了显示第一个指令,我也必须添加$作用域。firstDirective = true;在主控制器中,而不是在指令的控制器中

这是因为你的指令的作用域是隔离的,$scope.firstDirective$scope.secondDirective在指令的父作用域上。

简单的答案是使用$scope.$parent.firstDirective$scope.$parent.secondDirective

我个人会这样设置:

app.controller('mainCtrl', function($scope){
    $scope.show = {
        'firstDirective': true,
        'secondDirective': false
    };
});
app.directive('newDirective',function(){
// Runs during compile
return {
    restrict: 'E',
    templateUrl: 'test.html',
    scope: {
        passvar: '@',
        show: '=showDirectives',
        shows: '@',
        hides: '@'
    },
    controller: function ($scope) {
        $scope.content= 'Random Content';
        $scope.otherOne = function(){
            $scope.show[$scope.hides] = false;
            $scope.show[$scope.shows] = true;
        }
    }
};
});

和模板

<body ng-controller="mainCtrl">
<new-directive ng-show="show.firstDirective" show-directives="show" shows="secondDirective" hides="firstDirective" passvar="first passing value"></new-directive>
<new-directive ng-show="show.secondDirective" show-directives="show" shows="firstDirective" hides="secondDirective" passvar="second passing value"></new-directive>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>