我创建了一个指令来包装一个jQuery插件,并从控制器向指令传递一个配置对象以供插件使用。(正常工作)
在配置对象中有一个回调函数,我想在事件发生时调用它。(正常工作)
在回调函数中,我想修改控制器$scope上的属性,但这并不起作用。由于某种原因,Angular不能识别属性已更改,这使我相信回调函数中的$scope与控制器的$scope不同。我的问题是我不知道为什么。
有人能指点我正确的方向吗?
在配置对象中有一个回调函数,我想在事件发生时调用它。(正常工作)
在回调函数中,我想修改控制器$scope上的属性,但这并不起作用。由于某种原因,Angular不能识别属性已更改,这使我相信回调函数中的$scope与控制器的$scope不同。我的问题是我不知道为什么。
有人能指点我正确的方向吗?
app.js
var app = angular.module('app', [])
.directive('datepicker', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
// Uncommenting the line below causes
// the "date changed!" text to appear,
// as I expect it would.
// scope.dateChanged = true;
var dateInput = angular.element('.datepicker')
dateInput.datepicker(scope.datepickerOpts);
// The datepicker fires a changeDate event
// when a date is chosen. I want to execute the
// callback defined in a controller.
// ---
// PROBLEM:
// Angular does not recognize that $scope.dateChanged
// is changed in the callback. The view does not update.
dateInput.bind('changeDate', scope.onDateChange);
}
};
});
var myModule = angular.module('myModule', ['app'])
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.dateChanged = false;
$scope.datepickerOpts = {
autoclose: true,
format: 'mm-dd-yyyy'
};
$scope.onDateChange = function () {
alert('onDateChange called!');
// ------------------
// PROBLEM AREA:
// This doesnt cause the "date changed!" text to show.
// ------------------
$scope.dateChanged = true;
setTimeout(function () {
$scope.dateChanged = false;
}, 5000);
};
}]);
HTML
<div ng-controller="MyCtrl">
<p ng-show="dateChanged">date changed!</p>
<input type="text" value="02-16-2012" class="datepicker" datepicker="">
</div>
element.data('datepicker').getDate()
中。我对AngularJS还很陌生,如果我说错了,请原谅我,但ng-model是用于表单元素的。有什么适当的替代方案吗? - simshaunng-model
,也可以硬编码更新控制器范围内的变量,或者使用任何自定义属性来存储变量名称(例如,在页面的多个位置使用此属性)。如果有更多问题,可以创建一个包含<a>
标签实现的更新版本。在指令中,在scope.$apply
调用中以数据元素来源轻松修改。保持相同的$watch
方法论。 - charlietflscope[attrs.ngModel]
,因为 $parse 可以处理obj.myDate
这种 ng-model 值,参见 fiddle。在这种情况下,scope[attrs.ngModel]
不起作用。 - Mark Rajcok