I want to create a $scope function that will only manipulate the variables that it receives.
I've made a working Plunker to test things out.
I have a ng-repeat that is just listing names and id of kitties. I also have an input form to receive a name of a new kitty. Then, I have 3 buttons, each one accessing a different $scope function that will manipulate the $scope in different ways.
The goal of every function is to read the name of the kitty from the input form, read the last id used on the kitties array, assign that id+1 to the new kitty, push the new kitty to the array of kitties and delete the form data.
The first function,
$scope.addFullScope()
, will receive nothing as arguments and will read and manipulate everything from$scope
.The second function,
$scope.addJustDelete(kitty, kitties)
, will receive both the newkitty
and thekitties
array as argument. But, on the end, to clean up the form, it will do$scope.kitty = undefined
The third function,
$scope.addNoScope(kitty, kitties)
, will receive both the newkitty
and thekitties
array as argument. But, on the end, to clean up the form, it will dokitty = undefined
. But the form won't clean up! and everything will star to bug out.
How can I make this third function, or something like it, work so I have a fully independent function to work with?
Appendix:
Html:
<body ng-app='app' ng-controller="ctrl">
<h3 ng-repeat="kitty in kitties">
{{kitty.name}}: {{kitty.id}} //Kitties list
</h3>
<input placeholder='Kitty name to add' class='form form-control'
type="text" ng-model="kitty.name" />
<h3> $scope use on adding kitty:</h3>
<button ng-click="addFullScope()">Full Scope.</button>
<button ng-click="addJustDelete(kitty, kitties)">Just delete.</button>
<button ng-click="addNoScope(kitty, kitties)">None. Buggy</button>
</body>
Controller:
.controller('ctrl', function($scope) {
$scope.kitties = [
//Let's imagine kitties in here.
{name: 'Purple kitty', id:35},
//Kittie 36 died in a car accident. :(
{name: 'Rodmentou cat', id: 37},
{name: 'Fatty kitty', id: 38}
];
$scope.addFullScope = function () {
var size = $scope.kitties.length;
var id = $scope.kitties[size-1].id + 1;
$scope.kitty.id = id;
$scope.kitties.push($scope.kitty);
$scope.kitty = undefined;
};
$scope.addJustDelete = function (kitty, kitties) {
var size = kitties.length;
var id = kitties[size-1].id + 1;
kitty.id = id;
kitties.push(kitty);
$scope.kitty= undefined;
};
$scope.addNoScope = function (kitty, kitties) {
var size = kitties.length;
var id = kitties[size-1].id + 1;
kitty.id = id;
kitties.push(kitty);
kitty = undefined; //Don't work
};
});