javascript - How to assign varaible in ng-model on input based on condition -
i want assign ng-model variable based on condition. example:
<input type="text" ng-model="item.model[multilang]" >
$scope.multilang
can "eng","jp"(languages)
or false
. example, if multilang = "eng"
, user type in input "hello"
,the result
item.model = {eng:"hello"}
the problem when $scope.multilang = false
, want result be
item.model = "hello"
i can't find way achieve above result. think 1 solution changing ng-model based on $scope.multilang
when it's false,it change ng-model of input = ng-model="item.model"
don't know how this.
edited thought of 1 solution:
<input ng-if="multilang" type="text" ng-model="item.model[multilang]" > <input ng-if="!multilang" type="text" ng-model="item.model" >
but there better way achieve ?
angular flexible , powerful framework. should use custom directive , ngmodel's getter/setter option.
directive without ngmodel's getter/setter may this:
<input type="text" ng-model="val" multilang="multilang" multilang-model="item.model">
directive code:
.directive('multilang', [function(){ return { restrict: "a", require: "ngmodel", scope: { multilang: "=", multilangmodel: "=" }, link: function(scope, element, attr, ngmodel){ ngmodel.$viewchangelisteners.push(function()){ var value = ngmodel.$modelvalue; if(scope.multilang !== false) { if(typeof scope.multilangmodel == 'undefined') scope.multilangmodel = object.create(null) scope.multilangmodel[scope.multilang] = value } else { scope.multilangmodel = value } }) } } }])
in case of using ngmodel's getter/setter
<input type="text" ng-model="val" multilang="multilang" multilang-model="item.model" ng-model-options="{ gettersetter: true }">
directive code:
.directive('multilang', [function(){ return { restrict: "a", scope: { multilang: "=", multilangmodel: "=", val: "=ngmodel" }, link: function(scope, element, attr){ scope.val = function(newvalue) { if(scope.multilang !== false) { if(typeof scope.multilangmodel == 'undefined') scope.multilangmodel = object.create(null) return arguments.length ? (scope.multilangmodel[scope.multilang] = newvalue) : scope.multilangmodel[scope.multilang]; } else { return arguments.length ? (scope.multilangmodel = newvalue) : scope.multilangmodel; } } } } }])
in opinion, second 1 better. has 2 way binding item.model
, changes input
value when item.model
changed in other place of code.
Comments
Post a Comment