我遇到有关 mdl-textfield
行为的问题
在下面的 plnkr 上,按照以下步骤操作:
- 点击“小组工作”
- 在一项上点击“复制”
- 看看最后出现了与 ngModel 关联的新文本字段(angular.copy),但文本字段的行为很奇怪,即使有一个值,标签也不会 float ,但如果您单击文本字段,它就会出现按预期 float 。如果您修改该字段,该行为将保留,但如果您在没有任何修改的情况下退出它,标签将返回并覆盖。
http://plnkr.co/edit/MUI2iBslIH9jd4fgEQPL?p=preview
ngView
内容
<div data-ng-controller="MainCtrl">
<section data-ng-repeat="fo in foo">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="sample1" data-ng-model="fo.bar"/>
<label class="mdl-textfield__label" for="sample1">{{fo.bar}}</label>
<span ng-if="$last" ng-init="update()"></span>
</div>
<button ng-click="focopy(fo)">Copy</button>
</section>
<div data-ng-show="datacopy.edit" class="input-field">
<input type="text" id="ex1" data-ng-model="datacopy.bar" />
<label for="ex1">label</label>
</div>
</div>
Angular 模块
var app=angular.module('plunker', ['ngRoute'])
app.config(function($routeProvider){
$routeProvider
//Root URL
.when('/',{template:'<p>Coucou</p>'})
.when('/groups',{templateUrl:'groups.html'})
.when('/groupsnotworking',{templateUrl:'groupsnotworking.html'})
});
app.controller('MainCtrl', function($scope,$timeout) {
$scope.foo = [
{bar: 'world'},{bar:'toto'},{bar:'toto'}
];
$scope.groups=$timeout(function(){
$scope.groups=$scope.foo
},1000);
$scope.update=function(){
componentHandler.upgradeAllRegistered();
};
$scope.datacopy={};
$scope.focopy=function(data){
$scope.datacopy=angular.copy(data);
$scope.datacopy.edit=true;
};
});
希望它足够清楚。 我试图将其发布在 Material Design lite 的 github 上,认为这是一个错误,但我已经在这里被踢掉了...... 谢谢
最佳答案
当您在注册 mdl 组件后设置 mdl-textfield__input
的 ng-model
值时,mdl-textfield
会没有得到 is-dirty
类,因此行为不正常。
您可以在 `mdl-textfield__input 字段上使用此指令:
"use strict";
(function(){
let mdlTfFix = () => {
return {
restrict: "C",
require: "ngModel",
link: ($scope, $element, $attrs, ngModelCtrl) => {
$scope.$watch(() => {
return ngModelCtrl.$modelValue;
}, (newVal, oldVal) =>{
if(typeof newVal !== "undefined" && newVal !== "" && newVal !== oldVal){
$element.parent().addClass("is-dirty");
}
else{
$element.parent().removeClass("is-dirty");
}
});
}
};
};
mdlTfFix.$inject = [];
app.directive("mdlTextfieldInput", mdlTfFix);
})();
关于angularjs - mdl-textfield 不考虑 ngModel 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31638890/