angularjs - Binded scope not change correctly -
i have directive composite of input , select tags source code available in plunker
i newbie in angularjs , first directive after read tutorials. when change select options binded scope item1 not change correctly!!!! expect item1 must updated selected item in selectedchanged function
thanks or improve
codecombo directive template :
<span> <input ng-model="code" ng-change="codechanged()"> <select ng-model="selecteditem" ng-change="selectchanged()" ng-options="item item[propertytitle] item in list" class="codecombo-select"></select> </span>
codecombo script :
app.directive('codecombo', function($compile) { return { restrict:'a', scope:{ propertyid:'@', propertycode:'@', propertytitle:'@', list:'=' , selecteditem:'=', selectedchanged:'&' }, templateurl:'template.html', link: { pre: function (scope, element, attrs, controller) { /*make property optional*/ if(!attrs.propertytitle) attrs.propertytitle="title"; if(!attrs.propertyid) attrs.propertyid="id"; if(!attrs.propertycode) attrs.propertycode="code"; }, post: function (scope, element, attrs, controller) { var select=element.find('select'); var input=element.find('input'); /*some code delete save space ...*/ scope.code; /*select option changed*/ scope.selectchanged=function(){ console.log('select-changed'); console.log(scope.selecteditem); if(scope.selecteditem!==null){ fillselectedproperties(scope.selecteditem); } else emptyselectedproperties(); scope.selectedchanged(); } /*input text changed*/ scope.codechanged=function(){ console.log('code-changed'); scope.selecteditem=findbycode(scope.list,scope.code); console.log(scope.selecteditem); scope.selectchanged(); } } } } });
codecombo usage in index.html :
<div codecombo list="testlist" selecteditem="item1" selectedchanged="selectedchanged()"></div>
this controller :
app.controller('mainctrl', function($scope) { $scope.testlist=[ {id:1,code:100,title:'item no.100'}, {id:2,code:200,title:'item no.200'}, {id:3,code:300,title:'item no.300'}, {id:4,code:400,title:'item no.400'} ]; $scope.selectedchanged=function(){ /* want staff item1 here , expect updated each selectedchanged seem has previous value */ console.log($scope.item1); $scope.title=$scope.item1.title; } });
for reason change listener (ng-change
) fires before update of field of external scope. scope synchronization implemented $watch
of variable in internal scope updates variable in external.
having said that, propose removing selectedchanged
attribute , implementing watch in parent controller. think achieves same result, less code:
$scope.$watch("item1", function(newval) { console.log($scope.item1); $scope.title = $scope.item1 != null ? $scope.item1.title : "-"; });
(by way note null
/undefined
check.)
forked plunk: http://plnkr.co/edit/3ur9n9feduxqu2xehfc8?p=preview
Comments
Post a Comment