I\'m trying to get the value from ngModel from my input through a directive, but I can\'t get the value.
Here is my code:
angular
.module(\'myapp\')
By this sample you can get the first ngModel Value and also onChange Values
var app = angular.module("app", []);
app.controller("controller", function ($scope) {
$scope.test = "hi";
});
app.directive("directiveName", function () {
return {
restrict: "A",
replace: true,
scope: {
directiveName: "="
},
require: "^ngModel",
link: function (scope, element, attr, ngModel) {
var firstValue = scope.directiveName;
console.log("firstValue", firstValue);
element.on("input propertychange", function () {
console.log("onchange", ngModel.$viewValue);
});
}
}
})
<!DOCTYPE html>
<html ng-app="app" ng-controller="controller as ctrl">
<head>
<title></title>
</head>
<body>
<input type="text" ng-model="test" directive-name="test" />
{{test}}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
You're very close, but you need to make a minor adjustment to your directive in order to be able to pass and access the ng-model
item.
angular
.module('myapp')
.directive('infoVal', myVal);
function myVal() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
console.log('ng-model value', ngModel.$viewValue);
}
}
};