T. Ferreira T. Ferreira - 5 months ago 10
jQuery Question

AngularJS: How to save variable in modal to my $scope?

I'm making a task management tool in AngularJS and I have a form that the user has to fill to create a new task. Here's a short version of it:

<div ng-controller="SubmitController">
<!-- Form -->
<form>
Title
<input type="text" ng-model="tasks.title">

ID
<input type="text" ng-model="tasks.id">

Type
<select ng-model="tasks.type">
<option value="" disabled selected></option>
<option value="Job">Job</option>
<option value="Maintenence">Maintenence</option>
<option value="Verification">Verification</option>
</select>

<!-- This button opens a modal to select the recurrence -->
<a class="btn modal-trigger" href="#modal4">Recurrence</a>

<!-- This button adds the task to the list -->
<a ng-click="add(tasks)" class="btn" type="submit" name="action">Add</a>
</form>
</div>


Here's how I save the task in my .js file:

$scope.add = function(tasks)
{
$scope.tasks.push
({
'id': tasks.id,
'title': tasks.title,
'type': tasks.type,
'recurrence_type': tasks.recurrence_type
});

localStorage.setItem('tasks',JSON.stringify($scope.tasks));
};


As you can see I'm saving the tasks in the local storage. This is only a temporary solution for testing purposes, the final version will save the tasks to a database.

Anyway, I also have to have a recurrence mechanism, hence that
tasks.recurrence_type
in my
$scope
, and the button to open the modal in the form.

Here's that modal:

<!-- Modal Structure -->
<div id="modal4" class="modal">
<div class="modal-content">
<form>
Repeats:
<select ng-model="tasks.recurrence_type">
<option value="" disabled selected></option>
<option value="Daily">Daily</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Yearly">Yearly</option>
</select>
</form>
</div>
</div>
<div class="modal-footer">
<a href="#" class=" modal-action modal-close btn">Save</a>
</div>




My question is: how do I save the recurrence type in that modal to the
$scope.tasks.recurrence_type
?

Answer

The scope of your modal and your template are different in this case. The solution to this problem is that you will have to use the $rootScope.tasks.