[英]How to update $scope using jquery?
I have a bootstrapper datepicker.我有一个引导程序日期选择器。 I am updating the value of textbox in hide
event.我正在更新hide
事件中文本框的值。 Textbox values changes successfully however $scope
doesn't update.文本框值更改成功但$scope
不更新。
Javascript Javascript
<script type="text/javascript">
$(document).ready(function () {
$('#btnAdd').datepicker({
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
dateFormat: 'dd/mm/yy'
}).on('hide', function (e) {
$('#hdnDays').val($(this).val());
$(this).val('Add');
});
})
</script>
HTML HTML
<input type="text" ng-model="c" id="hdnDays" />
<input type="button" class="btn btn-primary" id="btnAdd" value="Add" />
you can see that I am using ng-model="c"
which means $scope.c
should change, but it is not happening.你可以看到我正在使用ng-model="c"
这意味着$scope.c
应该改变,但它没有发生。
How to update $scope
variable from hide
event?如何从hide
事件更新$scope
变量?
in angular, DOM manipulation is done inside of a directive , this is becuase you get two important variables you could use in there, and will solve your problem:在 angular 中,DOM 操作是在指令内部完成的,这是因为您可以获得两个可以在其中使用的重要变量,并将解决您的问题:
you get a variable referencing your element, this way you do not have to relay on it's id, or some other selector,你得到一个引用你元素的变量,这样你就不必中继它的 id 或其他一些选择器,
most important, you get a reference to the scope of the element, and this way you could call scope.$apply()
when changes have been made in scope variables.最重要的是,您可以获得对元素范围的引用,这样您就可以在范围变量中进行更改时调用scope.$apply()
。
in your case, you should put your code in a directive, something like this:在您的情况下,您应该将代码放在指令中,如下所示:
app.directive('datePicker', function($parse) {
return {
restrict: 'E',
link: function (scope, element, attr) {
element.datepicker({
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
dateFormat: 'dd/mm/yy'
}).on('hide', function (e) {
scope.$apply(function(){
$parse(attr['ng-model'])(scope).assign(element.val());
element.val('Add');
});
});
}
};
});
and in the view:并在视图中:
<input type="button" class="btn btn-primary datePicker" value="Add" />
you might need to adjust this code depending on what it is exactly you need.您可能需要根据您的需要调整此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.