2016-08-31 5 views
2

私は指示を1ページに2回使用しています。ディレクティブの中で私はクリックすると最初のディレクティブを削除し、もう一方のディレクティブを表示するボタンを配置しました。しかし、ng-click機能が起動しても値はまったく変化しません。私は間違って何をしていますか?ここに私のHTMLコードです。angularjs指示文の中のボタンは機能しません

<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;メインコントローラーではなく、ディレクティブのコントローラーにはありません。

+0

範囲にのみディレクティブのスコープを参照している、あなたはおそらく$ rootscopeかを使用する必要があります$ scope。$ parentはメインコントローラの変数を変更します。 –

+0

別のディレクティブを隠す/表示するために特定のディレクティブが必要なのはなぜですか? 2つ以上のものがあればどうなりますか?コントローラーに表示する必要のあるディレクティブを決定させることができないのはなぜですか? – cbass

+0

これ以上のものは2つありません。そして、私がここに挙げたものよりも複雑になるでしょう。私は何が間違っているのかを理解するためにここに単純なものを追加しました。 – Aijaz

答えて

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> 
関連する問題