【问题标题】:ngModel formatters change the $scopengModel 格式化程序更改 $scope
【发布时间】:2015-05-20 17:29:58
【问题描述】:

有一个inputngModel,其中有$formatters$parsers -

link: function(scope, element, attrs, ngModel) {
    //format text going to user (model to view)
    ngModel.$formatters.push(function(obj) {
        return obj.first;
    });
}

在我对输入进行任何更改后,我错过了示波器上的这个模型,意思是 -{{person.first}} 什么都不显示。

这是完整的代码 -

var myAppModule = angular.module('myApp', []); 
	    myAppModule.controller('myCtrl',function ($scope) {
	    	$scope.person = {
				first: 'Alice',
				last: 'Bob'
			}
	    })
		.directive('myDrtv',function(){
			return {
				restrict: 'A', 
				require: 'ngModel',
				link: function(scope, element, attrs, ngModel) {
					var _ngModel = ngModel;
					//format text going to user (model to view)
				    ngModel.$formatters.push(function(obj) {
						return obj.first;
					});
					//format text from the user (view to model)
					ngModel.$parsers.push(function(value) {
						return value;
				    });
				}
						  
			}
		})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

	<div ng-app="myApp">
		<div ng-controller="myCtrl">
			Name : <input my-drtv  ng-model="person" type="text"><br>
			{{person.first}}
    	</div>
		
	</div>

我怎样才能更改输入并仍然在{{person.first}} 中看到它?

请不要回答我,请将其更改为 ng-model="person.first" 我正在寻找解决方案 - ng-model="person"

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-model


    【解决方案1】:

    将您的输入更改为以下内容:

    <input my-drtv ng-model="person.first" type="text">
    

    他们以你的方式拥有它,你正在破坏 person 并将其从一个对象更改为一个字符串。

    编辑:如果您想将名字和姓氏分开,请执行以下操作:

    <input my-drtv ng-model="fullname" type="text">
    

    然后在link,观察变化并更新person

    scope.$watch('fullname', function(nv) {
      person.first = extractFirstName(nv);
      person.last = extractLastName(nv);
    });
    

    (我让你来提供 extract 函数)。

    【讨论】:

    • 感谢通知我它从对象更改为字符串。
    • @URL87,解释一下为什么你希望它是这样的。这不是 $formatters 和 $parsers 的典型用法
    • 我更新了我的答案,假设您希望能够对名字和姓氏都使用单个编辑字段。
    猜你喜欢
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2019-07-20
    相关资源
    最近更新 更多