I have a directive that returns me a select that when selected I want to get the value of the code from the controller and make an HTTP request.
Plunker: link
I have a directive that returns me a select that when selected I want to get the value of the code from the controller and make an HTTP request.
Plunker: link
You binded dadosCombo
, where you should actually bind selectedItem
You should keep an eye on changing the model, if you want to do some action after the item change happens ($ watch) Here's the solution:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.selectedItem = null;
$scope.$watch('selectedItem',function(newValue){
alert(newValue.codigo);
})
});
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: '='
},
link: link,
templateUrl:"sg-combo.html"
}
})
HTML Policy:
<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>
HTML BODY
<body ng-controller="MainCtrl">
<h1>Select em Directiva</h1>
<sg-combo selected-item="selectedItem"></sg-combo>
{{selectedItem}}
</body>
You can add the ng-change
directive to your select
and create a function to receive the data:
sg.combo.html
<div class="col-sm-4 control-label">
<label>{{label}}</label>
<select ng-model="dadosCombo" ng-change="pegarSelecionado(dadosCombo)" ng-options="item.nome for item in dados" class="form-control"></select>
</div>
App.js
app.controller('MainCtrl', function($scope) {
var codigo = $scope.selectedItem;
$scope.pegarSelecionado = function(item){
console.log(item);
//Faz a requisição Http
}
});
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',
controller: 'MainCtrl',
scope: {
dadosCombo: '='
},
link: link,
templateUrl:"sg-combo.html"
}
})
Notice that no controller
added a function: $scope.pegarSelecionado
that receives an item as a parameter. Within this function you can call the service that makes the http request passing item
to it.
In your directive, I added a section only, to say that controller
is MainCtrl
. If I did not do this the ng-change
I placed on your page would not be seen by controller
.