Angular JS - template of a directive with ng-model does not work inside ng-switch

0

To be more dynamic my directive I decided to include the category field that makes the selection of the type of template to be displayed. As it's just a select I thought of using ng-switch instead of multiple html files.

Plunker: link

index.html

<div ng-controller="MainCtrl">
<sg-combo 
  selected-item="selectedItem" categoria="filtro">
</sg-combo>

{{selectedItem}}

script.js

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

app.controller('MainCtrl', function($scope) {
  $scope.selectedItem = null;
    $scope.$watch('selectedItem',function(item){
    if (item != null){
        alert(item.nome); // Não exibe o alert qdo está com o switch
    }
  })
});

app.directive('sgCombo', function(){
    function link(scope, elem, attrs){    
            scope.dados = [
                {'codigo':1, 'nome':'teste1'},
                {'codigo':2, 'nome':'teste2'},
                {'codigo':3, 'nome':'teste3'}
            ];
    }

    return {
            restrict: 'E',          
        scope: {            
            selectedItem: '=',            
            categoria: '@'            
        },
        link: link,
        templateUrl:"sg-combo.html"
    }
})

sg-combo.html

<div ng-switch="categoria">
  <div ng-switch-when="filtro" class="col-sm-4 control-label">
     <div class="col-sm-4 control-label">
        <label>{{label}}</label>
        <select ng-model="selectedItem" ng-options="item.nome for item in dados" class="form-control"></select>
     </div>
  </div>
  <div ng-switch-when="anexo" class="col-sm-4 control-label">
     <div class="col-sm-4 control-label">
        <label>{{label}}</label>
        <select ng-model="selectedItem" ng-options="item.nome for item in dados" class="form-control"></select>
     </div>
  </div>
</div>
    
asked by anonymous 23.12.2015 / 22:05

1 answer

0

I joined your Plunker and noticed that it is working.

I adjusted some points in your project and got the expected result:

Follow the Plunker Altered: Plunker

Basically the changes were:

Put an identifier (title) in the templates, to know that the switch worked

 <div ng-switch-when="filtro" class="col-sm-4 control-label">Filtro
 <div ng-switch-when="anexo" class="col-sm-4 control-label">Anexo

I modified the index to bring the different template categories:

<sg-combo selected-item="selectedItem" categoria="filtro"></sg-combo>
{{selectedItem}}

<sg-combo selected-item="selectedItem2" categoria="anexo"></sg-combo>
{{selectedItem2}}

Modify your test of watch since the item is an object (not null) and it was entering if, null is the value of the object ...

$scope.selectedItem = {value:null};
$scope.selectedItem2 = {value:null};
$scope.$watch('selectedItem',function(item){
    if (item.value !== null) { /* code */ }

$scope.$watch('selectedItem2',function(item){
    if (item.value !== null) { /* code */ }
}

Hugs!

    
31.12.2015 / 01:00