1

Is it possible to change the binding expression on an ng-model directive dynamically?

This is what I'am trying to accomplish:

I have an input field that initially should propose a value (based on a value that the user entered some time ago -> "repetitions.lastTime"). This value should be bound initially. Then, if the user clicks on the input field, the proposed value should be copied to another property ("repetitions.current") on the scope. From now on, the input field should be bound to "repetitions.current".

Edit Plunker: http://plnkr.co/edit/9EbtnEYoJccr02KYUzBN?p=preview

HTML

<mo-repetitions mo-last-time="repetitions.lastTime" mo-current="repetitions.current"></mo-repetitions>

<p>current: {{repetitions.current}}</p>
<p>last time: {{repetitions.lastTime}}</p>

JavaScript

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.repetitions = {
      lastTime : 5,
      current : 0
    };
});

app.directive('moRepetitions', [function () {
    return { 
        restrict: 'E',
        scope: {
            moLastTime : "=",
            moCurrent : "="
        },
        link: function (scope, element, attrs, ngModel) {
          element.css("color", "gray");
          scope.activated = false;

          scope.activate = function () {
              if (scope.activated) 
                return;
              else 
                scope.activated = true;

              element.css("color", "black");

              scope.moCurrent = scope.moLastTime;

              //This is not working, because it apparently comes too late:
              attrs['ngModel'] = 'moCurrent';
            };
        },
        template: '<input ng-model="moLastTime" ng-click="activate()" type="number" />',
        replace: true
    };
}]);

Can someone point me on the right track?

1
  • Why don't you set the ng-model to moCurrent and just set the initial value to moLastTime using ng-init? Commented Jan 10, 2015 at 13:17

1 Answer 1

1

Created a plnkr

 element.attr('ng-model', 'moCurrent');
 $compile(element)(scope);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it works as expected. I slightly changed your solution to avoid relying on a parent element. element.attr('ng-model', 'moCurrent'); var clonedElement = $compile(element)(scope, function(clonedElement, scope) { element.replaceWith(clonedElement); clonedElement[0].focus(); });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.