2017-05-22 25 views
0

いくつかの入力ボタンをクリックして特定のdivのコントローラを動的に変更する必要があります。angularjsの動的コントローラの変更

最初の方法では動作しますが、コントローラー自体で1つの要素の配列を置き換えると、2番目の方法では機能しません(下記のコードを参照)。

このような機能をより良い方法で実装するにはどうすればよいですか?


Plnkr with one-element array (works)

index.htmlを

<body ng-app="myApp"> 
<div ng-controller="MyCtrl"> 
    Hello, {{name}}! 
    <input type="button" value="click me" ng-click="changeCtrl(0)"/> 
    <input type="button" value="click me" ng-click="changeCtrl(1)"/> 
    <input type="button" value="click me" ng-click="changeCtrl(2)"/> 

    <div ng-repeat = "ctrl in curCtrl" ng-controller="ctrl"> 
     {{ blah }} 
    </div> 
</div> 
</body> 
</html> 

script.js

var myApp = angular.module('myApp', []); 

myApp.controller("MyCtrl", MyCtrl); 

function MyCtrl($scope) { 
    $scope.name = 'Username'; 

    $scope.ctrls = [ctrlA, ctrlB, ctrlC]; 
    $scope.curCtrl = [ctrlA]; 

    $scope.changeCtrl = function (idx) { 
     $scope.curCtrl = [$scope.ctrls[idx]]; 
    } 
} 

function ctrlA($scope) {$scope.blah = "One";} 
function ctrlB($scope) {$scope.blah = "Two";} 
function ctrlC($scope) {$scope.blah = "Three";} 

それは ng-repeat ng-repeatので破棄し、再コンパイルHTML配列参照の変更で動作します

Plnkr with controller instead (doesn't work)

index.htmlを

<body ng-app="myApp"> 
<div ng-controller="MyCtrl"> 
    Hello, {{name}}! 
    <input type="button" value="click me" ng-click="changeCtrl(0)"/> 
    <input type="button" value="click me" ng-click="changeCtrl(1)"/> 
    <input type="button" value="click me" ng-click="changeCtrl(2)"/> 

    <div ng-controller="curCtrl"> 
     {{ blah }} 
    </div> 
</div> 
</body> 
</html> 

script.js

var myApp = angular.module('myApp', []); 

myApp.controller("MyCtrl", MyCtrl); 

function MyCtrl($scope) { 
    $scope.name = 'Username'; 

    $scope.ctrls = [ctrlA, ctrlB, ctrlC]; 
    $scope.curCtrl = ctrlA; 

    $scope.changeCtrl = function(idx) { 
    $scope.curCtrl = $scope.ctrls[idx]; 
    } 
} 

function ctrlA($scope) {$scope.blah = "One";} 
function ctrlB($scope) {$scope.blah = "Two";} 
function ctrlC($scope) {$scope.blah = "Three";} 

答えて

0

$element$compileサービスを使用して、配列なしで同じ結果が必要な場合は、手動でコンパイルする必要があります。それはあなたのコントローラーで行うことができますが、指示が良いかもしれません。

これを達成するためにクライアント側のルーティングを利用することもできます(ネストされた状態を許可するui-routerがあります)。

は、これらの答えをチェックアウト:

Dynamic NG-Controller Name

Dynamically assign ng-controller on runtime

そうしないと、あなたはng-if$timeoutで迅速なハックを使用することができます。

$scope.changeCtrl = function(idx) { 
    // ng-if sees null and destroys the HTML 

    $scope.curCtrl = null; 

    $timeout(function() { 
     // ng-if sees a new object and re-compiles the HTML 

     $scope.curCtrl = $scope.ctrls[idx]; 
    }); 
} 

<div ng-if="curCtrl" ng-controller="curCtrl"> 
    {{ blah }} 
</div> 
+0

おかげでたくさん!私は角度がコントローラの変更を両方のケースで監視していないことを確認したかっただけです。私はそれが1要素アレイによってng-repeatで機能したという事実に戸惑いましたが、あなたは今私のためにそれを明確にしました。ありがとう。 – Lelby

+0

よろしくお願いいたします。これがあなたの質問に答えたなら、それを受け入れられた回答としてマークしてください。 –

関連する問題