3

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.

2
  • The answers are right about $apply but the code you posted is full of other problems too. Syntax errors like function(){ restrict: 'A', there is not much to click in empty '<ul>' element, parameters elem and scope are in the wrong order in the link function and in the end, when this finally works, it will just show bunch of bullets (if even that, depends on your css) because there is nothing inside the '<li>'. Commented May 5, 2016 at 16:34
  • Sorry My mistake. Actually it is E. Also parameter order is wrong. Thanks all for the answer. I have updated my code and it is working fine now :) Commented May 5, 2016 at 16:59

2 Answers 2

1

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>'
});
Sign up to request clarification or add additional context in comments.

Comments

1

Note, that arguments in link function go in order just like below: link: function (scope, elem, attrs)

Try to use $apply method:

elem.bind('click',function(){
 scope.$apply(function(){
        scope.vModel=model.slice(0,20);
      }); 
});

And the best way to catch click event is use angular ng-click directive: https://docs.angularjs.org/api/ng/directive/ngClick

Comments

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.