Ser*_*rgi 5 twitter-bootstrap angularjs angularjs-directive
我是AngularJS的新手,这是我第一次写指令.
我正在尝试使用AngularJS 使Bootstrap Year Calendar工作.它是一个jQuery插件,用于显示带约会的日历.
我写了这个指令来创建日历:
app.directive('calendarScheduler', [function () {
return {
restrict: 'A',
scope: {
calendarData: '='
},
link: function (scope, element, attrs, ctrl) {
element.calendar({
enableRangeSelection: true,
dataSource: scope.calendarData
});
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
数据从此控制器传递给指令:
var app = angular.module('App', [])
app.controller('UserCtrl', ['$scope',
function($scope) {
$scope.User = {};
$scope.User.eventsData = [];
init();
$scope.User.addData = function(startDate, endDate) {
$scope.User.eventsData.push({
id: 2,
name: 'Apple Special Event',
location: 'San Francisco, CA',
startDate: new Date(2016, 6, 28),
endDate: new Date(2016, 6, 29)
});
};
function init() {
$scope.User.eventsData = [
{
id: 0,
name: 'Google I/O',
location: 'San Francisco, CA',
startDate: new Date(2016, 4, 28),
endDate: new Date(2016, 4, 29)
},
{
id: 1,
name: 'Microsoft Convergence',
location: 'New Orleans, LA',
startDate: new Date(2016, 2, 16),
endDate: new Date(2016, 2, 19)
}
];
}
}]);
Run Code Online (Sandbox Code Playgroud)
这是HTML:
<body ng-app="App">
<div ng-controller="UserCtrl">
<div
calendar-scheduler
id="calendar"
class="calendar"
calendar-data="User.eventsData">
</div>
<button data-ng-click="UserHoliday.addData();">Add Data</button>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
如果在创建指令时传递数据,则一切正常,但如果单击按钮向日历添加更多数据,则不会更新显示的数据(它应显示一个新约会).这也不显示使用$ http加载的数据.我已经尝试了$ scope.$ apply()来更新$ scope,包括控制器和指令,但它会抛出一个错误"$ apply has in progress".
正如我所说,我是AngularJS的新手,我不知道如何使这项工作,或者如果我在这里遗漏了一些东西.
希望你能帮忙.谢谢.
您只需绑定数据一次,因此它永远不会更新。相反,“观察”数据收集:
app.directive('calendarScheduler', [function () {
return {
restrict: 'A',
scope: {
calendarData: '='
},
link: function (scope, element, attrs, ctrl) {
function init() {
element.calendar({
enableRangeSelection: true,
dataSource: scope.calendarData
});
}
// re-init when data is changed
scope.$watchCollection("calendarData", function(val) {
// according to the documentation, data can be updated by doing:
element.data("calendar").setDataSource(val);
});
init();
scope.$on("$destroy", function() {
// not sure if this is supported by the library,
// but is a best practice to prevent memory leaks
element.calendar("destroy");
});
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
403 次 |
| 最近记录: |