我已经尝试了各种方法来触发表单的ng-model函数。我正在使用bootstrap datepicker。我需要引导日期选择器在选择日期时触发ng模型值更新,请告诉我如何使用外部库或外部事件与ng模型进行交互?
这是我的代码示例。
这不是很复杂。
/// <reference path="../../typings/tsd.d.ts" />
var app = angular.module("DatePick", []);
var doc = document;
app.controller("AppCtrl", [
"$scope", "$q", "$http",
function($scope, $q, $http){
var appCtrl = this;
appCtrl.name = "Jesse App";
$scope.$on("pickerChange", function(evt, data){
$scope.$apply(function(){
$scope.form[data.key] = data.value;
console.log(data);
})
})
}
]);
var $scope;
doc.addEventListener("DOMContentLoaded", function(e){
angular.bootstrap(doc.querySelector("html"), ["DatePick"]);
var element = document.querySelector("form");
$scope = angular.element(element).scope();
});
$(document).ready(function(){
$("input:text").datepicker().change(function(e){
$scope.$emit("pickerChange", {key:$(e.currentTarget).attr('name'), value:$(e.currentTarget).val()})
})
$(".trigger").click(function(e){
var input = $("input[type=text]");
input.val('xxx');
input.trigger('input');
})
})
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="AppCtrl as app">
<div class="container">
<h3>{{app.name}}</h3>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit et, nulla, voluptates adipisci commodi, itaque ipsam earum hic ipsa qui nam. Itaque nulla, aut quod sit dignissimos explicabo laborum, mollitia!
</div>
<div class="container">
<form novalidate name="form">
<div ng-show="form.date.$dirty">
<div ng-show="form.date.$valid">valid</div>
<div ng-show="form.date.$invalid">invalid</div>
</div>
<input type="text" name="date" ng-model="date" class="form-control" ng-pattern="/[\d|\/]{5,}/" required>
<div ng-show="form.date2.$dirty">
<div ng-show="form.date2.$valid">valid</div>
<div ng-show="form.date2.$invalid">invalid</div>
</div>
<input type="text" name="date2" ng-model="date2" class="form-control" ng-pattern="/[\d|\/]{5,}/" required>
</form>
<div class="btn btn-primary trigger">trigger</div>
</div>
</body>
</html>
&#13;
触发按钮的原因是我试图查看是否可以使用jquery来触发输入并获得更新模型的角度,但这是必要的。