user2580925 user2580925 - 7 months ago 29
Javascript Question

ng-repeat in angular directive

I am trying to create a custom select directive with some extra functionality.

.directive('singleSelect',function(){
restrict:'A'
scope:{
model:'='
}
link:function(elem,scope,attrs){
elem.bind('click',function(){
scope.vModel=model.slice(0,20);
});
controller:function($scope)
{
//some more manipulation with model and assign to vModel
}
template:'<ul><li ng-repeat="item in vModel"></li><ul>'
});


The problem is that I am assigning the value to vModel but it is not getting updated in the template.

Answer

This is happening because you are updating your scope variable inside a jQuery selector. You need to use $scope.$apply to start the digest cycle which will update your model.

Try this:

.directive('singleSelect',function(){
restrict:'A'
scope:{
model:'='
}
link:function(scope, elem, attrs){
elem.bind('click',function(){
scope.$apply(function(){
   scope.vModel=model.slice(0,20);
})
});
controller:function($scope)
{
//some more manipulation with model and assign to vModel 
}
template:'<ul><li ng-repeat="item in vModel"></li><ul>'
});