使用指令动态更改Angular JS中的模型绑定?

时间:2015-01-10 12:10:38

标签: angularjs angularjs-directive angular-ngmodel

是否可以动态更改ng-model指令上的绑定表达式?

这就是我想要完成的事情:

我有一个输入字段,最初应该提出一个值(基于用户之前输入的值 - >" repetitions.lastTime")。该值最初应该绑定。然后,如果用户单击输入字段,则应将建议的值复制到范围上的另一个属性(" repetitions.current")。从现在开始,输入字段应绑定到" repetitions.current"。

编辑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
    };
}]);

有人能指出我走在正确的轨道上吗?

1 个答案:

答案 0 :(得分:1)

创建了plnkr

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