ngModel格式化程序更改$ scope

时间:2015-05-20 17:29:58

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

input ngModel $formatters $parserslink: 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"我正在寻找解决方案 - List

1 个答案:

答案 0 :(得分: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个功能。)