Corné Strijkert Corné Strijkert - 27 days ago 17
AngularJS Question

How to update Angular scope properties when they are passed into directives?

I have functionality where developers can add custom Angular views where they can bind properties to the $scope.settings object. When clicking on the save button the $scope.settings object will be converted to JSON and saved to the database. Something like this will be the result:

{
"name": "bob",
"age": "25"
}


As long as I add elements like
<input type="text" ng-model="settings.name" />
everything goes as expected.

But, now I want to add directives like this:

<umb-property property="property in properties">
<umb-editor model="property"></umb-editor>
</umb-property>


With the following code:

$scope.properties = [
{
label: 'Name',
alias: 'name',
view: 'textbox',
value: $scope.settings.name
},
{
label: 'Age',
alias: 'age',
view: 'number',
value: $scope.settings.age
}
];


The 'editor' directive loads views in place based on the 'view' property. The views are third party. The editors are loaded in a dialog. After submission of the settings dialog, the following line of code will convert the settings to JSON:

$scope.dialog = {
submit: function (model) {
var settingsJson = JSON.stringify(model.settings);
},
close: function (oldModel) {
//
}
};


In this case I cannot parse the $scope.settings to JSON, because the $scope.settings.name is not updated anymore. The $scope.editorModel.value was updated instead.

How can I bind the $scope.editorModel.value to $scope.settings.name?
I don't want to end up with a solution where I must update all $scope.settings values with the corresponding values from the editor models, because I want to support the dynamic way to convert the $scope.settings to a JSON value in the database.

Answer

For example I dont want to do: $scope.settings.name = $scope.properties[0].value

Use property accessors:

for (var i=0; i<properties.length; i++) {
    $scope.settings[$scope.properties[i].alias] = $scope.properties[i].value;
};

HTML

<div ng-repeat="prop in properties">
    <input ng-model="prop.value">
</div>