Dynamically assign ng-model

前端 未结 5 1340
一整个雨季
一整个雨季 2020-11-29 19:49

I\'m trying to generate a set of check-boxes from an object array. I\'m aiming to have the check-boxes dynamically map their ng-model to a property of the new object that wi

5条回答
  •  清酒与你
    2020-11-29 20:07

    EDIT As correctly noted in the comments using this with ng-change requires a "dummy" ng-model to be present beforehand. It should however be noted that apparently with 1.3 the required options have been provided by the framework. Please check out https://stackoverflow.com/a/28365515/3497830 below! /EDIT

    Just in case you are like me stumbling over a simple case while having a more complex task, this is the solution I came up with for dynamically binding arbitrary expressions to ng-model: http://plnkr.co/edit/ccdJTm0zBnqjntEQfAfx?p=preview

    Method: I created a directive dynamicModel that takes a standard angular expression, evaluates it and links the result to the scope via ng-model and $compile.

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.data = {};
      $scope.testvalue = 'data.foo';
      $scope.eval = $scope.$eval;
    });
    
    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.data = {};
      $scope.testvalue = 'data.foo';
      $scope.eval = $scope.$eval;
    });
    
    app.directive('dynamicModel', ['$compile', function ($compile) {
        return {
            'link': function(scope, element, attrs) {
                scope.$watch(attrs.dynamicModel, function(dynamicModel) {
                    if (attrs.ngModel == dynamicModel || !dynamicModel) return;
    
                    element.attr('ng-model', dynamicModel);
                    if (dynamicModel == '') {
                        element.removeAttr('ng-model');
                    }
    
                    // Unbind all previous event handlers, this is 
                    // necessary to remove previously linked models.
                    element.unbind();
                    $compile(element)(scope);
                });
            }
        };
    }]);
    

    Usage is simply dynamic-model="angularExpression" where angularExpression results in a string that is used as the expression for ng-model.

    I hope this saves someone the headache of having to come up with this solution.

    Regards, Justus

提交回复
热议问题