javascript - In Angular models, can you switch value type between JSON Object and String? -
javascript - In Angular models, can you switch value type between JSON Object and String? -
i have application @ work working on requires me display various fields based on value of associated rule.itemtype
. issue coming across unable modify model info in ng-repeat
if previous set value in rule.value
string
object displaying fields require object
. when seek assign new values returns: typeerror: cannot assign read property 'course' of abc123
.
i did find if value object
display string
of [object object]
, assuming comes object.prototype.tostring()
function reading about, , if changed replace rule.value
new string
object. though direction works, if needing string
object
end @ above mentioned issue.
i have attached sample code demonstrate trying below plus data. forked, modified, , linked replier's plunker can see in action:
http://plnkr.co/edit/v4gsyc6mbyeggyjppvnc?p=preview
javascript:
var app = angular.module('plunker', []); app.controller('appctrl', function ($scope) { $scope.rules = [ {id: 1, itemtype: 'cs', value: {course: 'abc', number: '123'}}, {id: 2, itemtype: 'sa', value: 'abc123'} ]; });
html, angular v1.3.0:
<body> <div ng-controller="appctrl app"> <div ng-repeat="rule in rules"> rule {{$index+1}} <!-- alter itemtype rule --> <select ng-model="rule.itemtype"> <option value="sa">string</option> <option value="cs">object</option> </select> <!-- fields shown if rule.itemtype (sa: string, cs: object) --> <input type="text" ng-if="rule.itemtype === 'sa'" ng-model="rule.value" /> <span ng-if="rule.itemtype === 'cs'"> <input ng-model="rule.value.course" /> <input ng-model="rule.value.number" /> </span> </div> </div> </body>
update 1:
added suggestion ryan randall utilize ng-change='changetype(rule)
provides appropriate behavior looking for, illustration plunker below.
http://plnkr.co/edit/bfahzj?p=preview
javascript changes:
// contributed by: http://stackoverflow.com/a/26702691/949704 $scope.typechange = function (rule) { if (rule.itemtype === 'cs') rule.value = {}; if (rule.itemtype === 'sa') rule.value = ''; };
html changes:
<!-- alter itemtype rule --> <select ng-model="rule.itemtype" ng-change="changetype(rule)"> <option value="sa">string</option> <option value="cs">object</option> </select>
one way avoid issue you're having explicitly set rule.value when rule.itemtype changes.
here's working plunker containing tweaks: http://plnkr.co/edit/rmfebe?p=preview
the next has been added select:
ng-change="typechange(rule)"
and next has been added controller:
$scope.typechange = function(rule) { if (rule.itemtype === 'cs') rule.value = {}; if (rule.itemtype === 'sa') rule.value = ''; };
javascript json angularjs type-conversion angular-ngmodel
Comments
Post a Comment