0

To become more dynamic my directive decided to include the category field that makes the selection of the type of template to be displayed. As it is only a select thought of using the switch - ng instead of several html files. (google translate)

Plunker: http://plnkr.co/edit/fnCJj15XJN1kQvKq1OtZ?p=preview

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 = {value: null};
  $scope.$watch('selectedItem',function(item){
  if (item != null){
    alert(item.nome); // does not display when updating
  }
 })
});

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.value" 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.value" ng-options="item.nome for item in dados" class="form-control"></select>
  </div>
 </div>
</div>
  • replied in **stackoverflow portugueses** https://pt.stackoverflow.com/questions/105410/angular-js-template-de-uma-directiva-com-ng-model-n%C3%A3o-funciona-dentro-de-ng-sw/106260#106260 – Alessandro Barros Jan 02 '16 at 13:13

2 Answers2

0

Try to make 'selectedItem' a part of an object. For instance:

In controller: $scope.options = {'selectedItem': someItem};

In template: ng-model="options.selectedItem"

Frane Poljak
  • 2,315
  • 23
  • 25
0

ng-switch adds a scope and you should use '.' in ng-model.

Community
  • 1
  • 1
Artem
  • 823
  • 8
  • 14
  • It is bad idea to change original code in question, so my answer may confuse somebody. Please check [original version](http://stackoverflow.com/posts/34533654/revisions) – Artem Dec 30 '15 at 17:26