这是我的带有 html 代码的 Angular js 应用程序
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
angular.module("demo", []).controller('DemoController', function ($scope) {
$scope.user = {
dateOfBirth: new Date(1970, 0, 1)
}
});
</script>
</head>
<body>
<div ng-app="demo" ng-controller="DemoController">
Date Of Birth:
<my-datepicker type="text" ng-model="user.dateOfBirth" />
<br />
Current user's date of birth: <span id="dateOfBirthDisplay">{{user.dateOfBirth}}</span>
</div>
</body>
</html>
它工作正常。但是当我向它添加指令时,它显示错误
Error: Argument 'DemoController' is not a function, got undefined
这是带有指令的完整代码
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
angular.module("demo", []).controller('DemoController', function ($scope) {
$scope.user = {
dateOfBirth: new Date(1970, 0, 1)
}
});
angular.module("demo", []).directive('myDatepicker', function ($parse) {
return {
restrict: "E",
replace: true,
transclude: false,
compile: function (element, attrs) {
var modelAccessor = $parse(attrs.ngModel);
var html = "<input type='text' id='" + attrs.id + "' >" +
"</input>";
var newElem = $(html);
element.replaceWith(newElem);
return function (scope, element, attrs, controller) {
var processChange = function () {
var date = new Date(element.datepicker("getDate"));
scope.$apply(function (scope) {
// Change bound variable
modelAccessor.assign(scope, date);
});
};
element.datepicker({
inline: true,
onClose: processChange,
onSelect: processChange
});
scope.$watch(modelAccessor, function (val) {
var date = new Date(val);
element.datepicker("setDate", date);
});
};
}
};
});
</script>
</head>
<body>
<div ng-app="demo" ng-controller="DemoController">
Date Of Birth:
<my-datepicker type="text" ng-model="user.dateOfBirth" />
<br />
Current user's date of birth: <span id="dateOfBirthDisplay">{{user.dateOfBirth}}</span>
</div>
</body>
</html>