【问题标题】:Change model binding in Angular JS dynamically using a directive?使用指令动态更改Angular JS中的模型绑定?
【发布时间】:2015-01-10 12:10:37
【问题描述】:

是否可以动态更改 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
    };
}]);

谁能指出我正确的轨道?

【问题讨论】:

  • 为什么不将 ng-model 设置为 moCurrent 并使用 ng-init 将初始值设置为 moLastTime?

标签: angularjs angularjs-directive angular-ngmodel


【解决方案1】:

创建了plnkr

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

【讨论】:

  • 谢谢,它按预期工作。我稍微更改了您的解决方案以避免依赖父元素。 element.attr('ng-model', 'moCurrent'); var clonedElement = $compile(element)(scope, function(clonedElement, scope) { element.replaceWith(clonedElement); clonedElement[0].focus(); });
猜你喜欢
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 2016-03-27
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多