AngularJS - 如何在自定义指令中更改 ngModel 的值? [英] AngularJS - how to change the value of ngModel in custom directive?

查看:31
本文介绍了AngularJS - 如何在自定义指令中更改 ngModel 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看我的指令:

angular.module('main').directive('datepicker', [
function() {
    return {
        require: '?ngModel',
        link: function(scope, element, attributes, ngModel) {
            ngModel.$modelValue = 'abc'; // this does not work
            // how do I change the value of the model?

那么,如何更改 ng-model 的值?

So, how do I change the value of the ng-model?

推荐答案

有不同的方法:

  1. $setViewValue() 更新视图和模型.大多数情况下就足够了.
  2. 如果您想断开视图与模型的连接(例如,模型是一个数字,而视图是一个带有千位分隔符的字符串),那么您可以直接访问 $viewValue$modelValue
  3. 如果您还想覆盖 ng-model 的内容(例如,指令更改小数位数,同时更新模型),请注入 ngModel: '=' 在作用域上设置 scope.ngModel
  1. $setViewValue() updates the view and the model. Most cases it is enough.
  2. If you want to disconnect view from the model (e.g. model is a number but view is a string with thousands separators) then you could access directly to $viewValue and $modelValue
  3. If you also want to overwrite the content of ng-model (e.g. the directive changes the number of decimals, updating also the model), inject ngModel: '=' on the scope and set scope.ngModel

例如

  return {
     restrict: 'A',
     require: 'ngModel',
     scope: {
         ngModel: '='
     },
     link: function (scope, element, attrs, ngModelCtrl) {

        function updateView(value) {
            ngModelCtrl.$viewValue = value;
            ngModelCtrl.$render(); 
        }

        function updateModel(value) {
            ngModelCtrl.$modelValue = value;
            scope.ngModel = value; // overwrites ngModel value
        }
 ...

链接:

这篇关于AngularJS - 如何在自定义指令中更改 ngModel 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆