angularjs指令内的按钮不起作用

时间:2016-08-31 20:46:38

标签: javascript html angularjs angular2-directives

我在一个页面中使用了两次指令。在指令内部,我放置了一个按钮,在单击时删除第一个指令并显示另一个指令。但即使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;
        }
    }
};
});

即使显示第一个指令,我也要添加$ scope.firstDirective = true;在主控制器中,而不是在指令的控制器中。

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为您的指令的范围是孤立的,$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>