martinoss
martinoss

Reputation: 5458

Change model binding in Angular JS dynamically using a directive?

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?

Upvotes: 1

Views: 1538

Answers (1)

dhavalcengg
dhavalcengg

Reputation: 4713

Created a plnkr

 element.attr('ng-model', 'moCurrent');
 $compile(element)(scope);

Upvotes: 1

Related Questions