使用指令动态更改 Angular JS 中的模型绑定?
Change model binding in Angular JS dynamically using a directive?
是否可以动态更改 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
};
}]);
有人能指出我正确的方向吗?
创建了 plnkr
element.attr('ng-model', 'moCurrent');
$compile(element)(scope);
是否可以动态更改 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
};
}]);
有人能指出我正确的方向吗?
创建了 plnkr
element.attr('ng-model', 'moCurrent');
$compile(element)(scope);