My Technical Notes

Tuesday, 19 May 2015

Angular: Populating the model from an input

To populate the Angular model (or $scope etc) from an input field, we have to use a directive that targets `input` elements:


(function() {
    var app = angular.module("MyModuleName", []);

    app.directive('input', [function() {
        return {
            restrict: 'E',
            require: '?ngModel',
            link: function postLink(scope, iElement, iAttrs, ngModelController) {
                if (iAttrs.value && ngModelController) {
                    ngModelController.$setViewValue(iAttrs.value);
                }
            }
        };
    }]);

})();

No comments: