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>
1

2 Answers 2

0

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

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

I see you edited the code, doing excatly what I suggested here. Did it work? If so, an upvote would be nice :)
0

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

1 Comment

It is bad idea to change original code in question, so my answer may confuse somebody. Please check original version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.