Giedrius
Giedrius

Reputation: 8550

How to get reference to model property by knowing it's path in angular js?

I'm quite new with angular js, situation is this: I have javascript datepicker, which is input with popup for date selection, input is bound to angular model.

Problem as I understand is that input value is changed from javascript, not from ui, so angular js does not know, that value has changed, so it does not update model value.

I've found sample with color picker, it would almost fit, except the fact, that I don't wish to hardcode what property to update.

I would imagine following workflow:
1. subscribe to all datepickers' onchanged event
2. when that event is fired, read model path from input (for example reading ng-model attribute value, may be there's better way?)
3. and use that path to update value in model. I could split path by using dot and access property using those parts, but I somehow think, that this should be already implemented in angular js (at least in inner routines).

Upvotes: 1

Views: 1419

Answers (2)

tschiela
tschiela

Reputation: 5271

You need $scope.$apply to inform AngularJS about the model change. I don't know which datepicker you really use, but may i can be look something like:

$($element).datepicker({
  .
  .
  .
}).on('changeDate', function(event){
  $scope.$apply(function(){
    $scope.date = event.date;  
  });
});

More about $apply in the AngularJS docs and in my opinion an excellent article from Jim Hoskins.

Upvotes: 1

Giedrius
Giedrius

Reputation: 8550

@Chandermani correctly noticed, that in color picker example I've mentioned, you can specify property to bind to in html, so it solves situation I've described.

Anyway I've looked up into source code of angular js and noticed, that $apply is much more clever than I thought, so answering to my question title, you can give complex expressions to $apply, like assignments:

 $('.date').datepicker()
    .on('changeDate', function(e) {
       var input = $(e.target).find('input');
       var currentScope = angular.element(input).scope();

       // exp will evaluate to something model.createdDate = '2013-08-06'
       var exp = input.attr('ng-model') + '="' + input.val() + '"';
       currentScope.$apply(exp);
    });

Upvotes: 0

Related Questions