在这种情况下(在控制器中)有什么简短的方法可以调用父作用域吗?
$scope.tables = [];
$scope.newTable = function(){
$scope.tables.push({name:"Table " + ($scope.tables.length+1),cols:[]});
$scope.selected = $scope.tables.length-1;
};
如果在$ scope.newTable中忽略$ scope有任何短路,则应缩短此代码。也许我不知道那个
答案 0 :(得分:3)
是的,您可以在控制器中定义一个对象,稍后您将向该对象公开该对象。类似的东西:
var tableHandler = {
selected: 0,
list: [],
newTable: newTable
};
function newTable()
{
var tableLength = tableHander.list.length;
var emptyTable = {name: "Table " + (tableLength + 1), cols: []};
tableHander.list.push(emptyTable);
tableHandler.selected = tableLength;
}
;
$scope.tableHandler = tableHandler;
然后在你的HTML中
<button ng-click="tableHandler.newTable()"></button>
重复和选择支持的另一个例子:
<ul>
<li ng-repeat="table in tableHandler.list" track by $index"
ng-class="{selected: tableHandler.selected === $index}">
{{table.name}}
</li>
</ul>