尝试从自定义指令中访问$modelValue
和$viewValue
时,我收到null
。
var demo = angular.module('demo', []);
demo.directive('dogInfo', function($parse) {
return {
restrict: 'E',
require: 'ngModel',
template: "<div> Dog's name: {{dogname}}<br>View Name: {{viewValue}}<br>Model Value: {{modelValue}}<br> Tag name: {{tagName}}</div>",
link: function (scope, element, attrs, controller) {
scope.viewValue = controller.$viewValue;
scope.modelValue = controller.$modelValue;
scope.tagName = controller.$name;
}
}});
function MyCtrl ($scope) {
$scope.dogname = 'Hero'; // now
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<div ng-app='demo'>
<p ng-controller='MyCtrl'>
<dog-info ng-model="dogname" name="Doggggyyy"/>.
</p>
</div>
我收到了这个输出:
Dog's name: Hero
View Name: null
Model Value: null
Tag name: Doggggyyy
答案 0 :(得分:1)
尝试这种方法:
demo.directive('dogInfo', function($parse) {
return {
restrict: 'E',
require: 'ngModel',
template: "<div> Dog's name: {{dogname}}<br>View Name: {{model.$viewValue}}<br>Model Value: {{modelValue}}<br> Tag name: {{tagName}}</div>",
link: function (scope, element, attrs, controller) {
scope.model = controller;
scope.viewValue = controller.$viewValue;
scope.modelValue = controller.$modelValue;
scope.tagName = controller.$name;
}
}});
注意我如何将数据传递给视图
答案 1 :(得分:0)
根据答案here,有三种可行的解决方案
1)使用$timeout
等到第一次摘要结束
$timeout(function() {
initialViewValue = controller.$viewValue;
}, 0)
2)使用scope.watch
const off = scope.$watch(attrs.ngModel, () => {
initialViewValue = controller.$viewValue;
off();
});
3)使用$parse
立即获取价值
const getter = $parse(attrs.ngModel);
let initialViewValue = getter(scope);
viewValue也可用作格式化程序回调中的参数
controller.$formatters.push(function(value) {
viewValue = value
});
如果您只想获取初始值
,则可能需要删除回调