Angular: Empty Fiddle
http://angularjs.org/
by Bretto
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc8.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css">
<div ng-controller="MainCtrl">
<button ng-click="addItem()">Add Item</button>
<div ng-repeat="item in stuff">
<button ng-click="removeItem(item)">Remove Item {{item}}</button>
</div>
<hr />
<bootstrap-tabs
items="stuff"
item-select="onItemSelect"
item-template="my-template"
item-title-attr="stuffTitle">
</bootstrap-tabs>
</div>
<script type="text/ng-template" id="my-template">
<button ng-click="parent.update(item)">Update!</button>
<br />
{{item.date}}
</script>
JavaScript
var myApp = angular.module('myApp',[]);
function MainCtrl($scope) {
$scope.stuff = [];
$scope.addItem = function() {
$scope.stuff.push({
stuffTitle: 'stuff '+$scope.stuff.length,
date: new Date()
});
};
$scope.removeItem = function(item) {
$scope.stuff.splice( $scope.stuff.indexOf(item), 1 );
};
//Problem here: It's calling functions for the directive scope
//while inside the template
$scope.update = function(item) {
item.date = new Date();
};
//This is never called, see below
$scope.onItemSelect = function(item) {
console.log(item,'selected');
};
}
myApp.directive('bootstrapTabs', function() {
var defaults = {
itemSelectedAttr: 'selected',
itemTitleAttr: 'title',
itemSelect: function(){}
};
var opts={};
var linkFn = function(scope, elm, attrs) {
opts = angular.extend(defaults, attrs);
};
var controllerFn = function($scope, $element, $attrs) {
//Have to watch items().length. If we just watch items(),
//the watch will never actually trigger itself
$scope.$watch('items().length', function(newLength, oldLength) {
var selectedItem;
//Instant select first item created in list
if (newLength == 1 && oldLength == 0) {
$scope.selectItem($scope.items()[0]);
}
//If an item was deleted and still atleast one item in the array
if (newLength < oldLength && newLength > 0) {
//get selected item (it might be gone from array)
selectedItem = $scope.selectedIdx < newLength ?
$scope.items()[$scope.selectedIdx] : null;
//if selected item is null, it was at the end
if (selectedItem === null) {
...