2

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.

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 Answer 1

3

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

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.

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I thought you're just trying to capture the updated value in your watcher, if you need to update the text field to some desired value, you need to call $render() as well after $setViewValue(). Updated my answer to reflect that.
Glad to be of help :)
Thank you so much friend :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.