如何使用angularjs中的自定义指令更新输入文本值

时间:2022-08-22 08:53:20

I am newer in angularjs. I am just trying to update the input txt value using custom Directive. But i cant. Here i have showed my code What i did wrong this code. Some one help me and explain how it is working.

我在angularjs是新来的。我正在尝试使用自定义指令更新输入txt值。但我不能。在这里,我向代码展示了我做错了什么。有人帮我解释它是如何工作的。

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl',MyCtrl);
function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.myTime = '10:59';
}


myApp.directive('myDirective', function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModel) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('value changed, new value is: ' + v);
               ngModel.$setViewValue('11')
               //scope.ngModel = '11'
               
            });
        }
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl">
  Hello, {{name}}!
    
    
    <input type="text" my-directive ng-model="myTime" name="customTime">
    
</div>

1 个解决方案

#1


3  

You should register your MyCtrl controller in your myApp module like below.

你应该在你的myApp模块中注册你的MyCtrl控制器。

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',MyCtrl);

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.myTime = '10:59';
}

If you need to update the text field value to some desired value, once you're done with the update in the watcher using $setViewValue(), you need to call $render() as well on NgModelController.

如果需要将文本字段值更新到某个期望的值,那么在使用$setViewValue()对监视程序中的更新完成之后,您还需要在NgModelController上调用$render()。

link: function (scope, element, attrs, ngModel) {
    scope.$watch(attrs.ngModel, function (v) {
        console.log('value changed, new value is: ' + v);
       ngModel.$setViewValue('11');
       ngModel.$render();
    });
}

Here's a Pen to check this change.

这是一支笔来检查这张零钱。

#1


3  

You should register your MyCtrl controller in your myApp module like below.

你应该在你的myApp模块中注册你的MyCtrl控制器。

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',MyCtrl);

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.myTime = '10:59';
}

If you need to update the text field value to some desired value, once you're done with the update in the watcher using $setViewValue(), you need to call $render() as well on NgModelController.

如果需要将文本字段值更新到某个期望的值,那么在使用$setViewValue()对监视程序中的更新完成之后,您还需要在NgModelController上调用$render()。

link: function (scope, element, attrs, ngModel) {
    scope.$watch(attrs.ngModel, function (v) {
        console.log('value changed, new value is: ' + v);
       ngModel.$setViewValue('11');
       ngModel.$render();
    });
}

Here's a Pen to check this change.

这是一支笔来检查这张零钱。