我试图通过指令从输入中获取ngModel的值,但我无法获得该值。
这是我的代码:
angular
.module('myapp')
.directive('infoVal', myVal);
function myVal() {
return {
link: function(scope, element, attrs, ctrl){
console.log("Ng Model value");
console.log(attrs.ngModel.$viewValue);
}
}
};
HTML输入:
<input type="text"
class="form-control"
name="info"
ng-model="formCtrl.infor"
info-val>
答案 0 :(得分:2)
通过此示例,您可以获得第一个ngModel值以及onChange值
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);
});
}
}
})
&#13;
<!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>
&#13;
答案 1 :(得分:1)
您非常接近,但您需要对指令进行微调,以便能够传递和访问ng-model
项。
angular
.module('myapp')
.directive('infoVal', myVal);
function myVal() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
console.log('ng-model value', ngModel.$viewValue);
}
}
};