javascript 如何使用 ng-model (With plnkr) 实现功能绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18384031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:42:42  来源:igfitidea点击:

How to achieve Functional binding with ng-model (With plnkr)

javascriptangularjs

提问by Rohit Bansal

I have a dob column and values comes in this is in yyyy-mm-dd format say 2013-01-01 and I need to show it in input box as 1 Jan. I can achieve this by writing a function and then return exact value from that function. But function could not be called from input box using ng-model where as it can be called using ng-bind in spans.I can understand that function calling in input box will break two way binding. But what other approach I can use for this.

我有一个 dob 列,其中的值是 yyyy-mm-dd 格式,比如 2013-01-01,我需要在输入框中将其显示为 1 Jan。我可以通过编写一个函数然后返回精确值来实现这一点从那个函数。但是无法使用 ng-model 从输入框调用函数,因为它可以在跨度中使用 ng-bind 调用。我可以理解在输入框中调用函数会破坏双向绑定。但是我可以使用什么其他方法来做到这一点。

http://plnkr.co/edit/pZDpypsxM1OA2JwFhjjp?p=preview

http://plnkr.co/edit/pZDpypsxM1OA2JwFhjjp?p=preview

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" >
    var app = angular.module('app', []);
    app.controller('AppCtrl', function ($scope) {
        $scope.dob = "2013-01-01";
        $scope.getDateOfBirth = function(dob){
            var months = ["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"]
            var split = dob.split("-");
            return parseInt(split[2])+" "+months[parseInt(split[2])-1];
        }
    });
</script>

<span ng-app="app" ng-controller="AppCtrl" ng-bind="getDateOfBirth(dob)"></span>

<input type="text" ng-model="getDateOfBirth(dob)"/>

回答by zs2020

You can use ng-init to assign the value returned by the function and assign it to a model:

您可以使用 ng-init 分配函数返回的值并将其分配给模型:

<input ng-init="myDOB = getDateOfBirth(dob);" type="text" ng-model="myDOB">

DEMO

DEMO

回答by dsmithco

You can use ng-init to set the value and ng-change to keep the value updated

您可以使用 ng-init 来设置值和 ng-change 来保持值更新

http://plnkr.co/edit/q1hg0R?p=preview

http://plnkr.co/edit/q1hg0R?p=preview

回答by bfregon

For dates, phone numbers, etc., you can use ui-mask. Hope this helps someone!

对于日期、电话号码等,可以使用 ui-mask。希望这对某人有帮助!