在 angular 指令中获取模型值
Getting model value in angular directive
我为 http://eonasdan.github.io/bootstrap-datetimepicker 编写了一个 angular 指令,我可以对 datetimepicker 进行操作更新我的模型,但是当我 运行 遇到问题时我试图在实例化期间使用我的模型中的值设置 datetimepicker 控件上的 defaultDate。
这是一个笨蛋:http://plnkr.co/edit/XUQSx7s0Fle2Xes77VrM?p=preview
script.js
var app = angular.module('app', []);
app.controller('DemoCtrl', function($scope) {
$scope.modelDate = new Date("01/01/2010");
});
app.directive('datetimepicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
// scope.$apply(); //This fixes the issue, but throws error in console
element.datetimepicker( {
defaultDate: ngModelCtrl.$modelValue
})
.on('dp.change', function(e) {
ngModelCtrl.$setViewValue(e.date);
scope.$apply();
});
}
};
});
index.html
的相关部分
<div class="container">
<div class="form-group col-xs-6">
<div class="input-group date" datetimepicker ng-model="modelDate">
<input type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
Date from model: {{modelDate}}
</div>
</div>
看起来问题出在实例化 datetimepicker 时,模型为空。在实例化 datetimepicker 之前执行 scope.$apply()
可以解决这个问题,但会在控制台中抛出一个错误,而且这似乎不是正确的方法。任何帮助将不胜感激!
在我们的作用域上强制调用 $apply 并不是最明智的做法。
也许您应该尝试将其推迟到下一个摘要周期?
使用实用程序库(如 Underscorejs),尝试以下操作:
_.defer(function(){scope.$apply();});
我为 http://eonasdan.github.io/bootstrap-datetimepicker 编写了一个 angular 指令,我可以对 datetimepicker 进行操作更新我的模型,但是当我 运行 遇到问题时我试图在实例化期间使用我的模型中的值设置 datetimepicker 控件上的 defaultDate。
这是一个笨蛋:http://plnkr.co/edit/XUQSx7s0Fle2Xes77VrM?p=preview
script.js
var app = angular.module('app', []);
app.controller('DemoCtrl', function($scope) {
$scope.modelDate = new Date("01/01/2010");
});
app.directive('datetimepicker', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
// scope.$apply(); //This fixes the issue, but throws error in console
element.datetimepicker( {
defaultDate: ngModelCtrl.$modelValue
})
.on('dp.change', function(e) {
ngModelCtrl.$setViewValue(e.date);
scope.$apply();
});
}
};
});
index.html
的相关部分<div class="container">
<div class="form-group col-xs-6">
<div class="input-group date" datetimepicker ng-model="modelDate">
<input type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
Date from model: {{modelDate}}
</div>
</div>
看起来问题出在实例化 datetimepicker 时,模型为空。在实例化 datetimepicker 之前执行 scope.$apply()
可以解决这个问题,但会在控制台中抛出一个错误,而且这似乎不是正确的方法。任何帮助将不胜感激!
在我们的作用域上强制调用 $apply 并不是最明智的做法。 也许您应该尝试将其推迟到下一个摘要周期?
使用实用程序库(如 Underscorejs),尝试以下操作:
_.defer(function(){scope.$apply();});