如何从指令更改输入的ngModel源?

时间:2014-07-22 13:52:08

标签: javascript angularjs angularjs-directive

我想更改由我的指令输入的ngModel管理的源(例如源变量)。 我想克隆一个可由表单编辑的对象,并在指令中进行此处理。

可能this jsfiddle会更好地解释你。 我所做的是:

<div ng-app="myApp">
<div ng-controller="SimpleController">
    <form change-original-model>

        <input ng-model="myModel.firstname" /><br/>
        <input ng-model="myModel.secondname" /><br/>

        I want <b>myModel</b> to be not changed:<br/>
        {{ myModel.firstname }}<br/>
        I want <b>newModel</b> to be cloned and changed by input:<br/>
        {{ newModel.firstname }}<br/>

    </form>
</div>

angular.module('directives', []);

angular.module('directives').controller('SimpleController', function($scope) {
    $scope.myModel = { firstname: 'Sady', secondname: 'Sherozi' };
});

angular.module('directives').directive('changeOriginalModel', 
    function($parse) {
      return {
        require: '?ngModel',
        link: function(scope, element, attrs, controller) {

            var ngModel = $parse(attrs.ngModel)(scope);
            scope.newModel = angular.copy(ngModel);

            $(element).find("input").each(function(){
                form_elements = $(this).attr("ng-model");
                if (form_elements) {
                    var replace_input_data = form_elements.replace(attrs.ngModel + '.', "newModel." );
                    $(this).attr("ng-model", replace_input_data);
                }
            });
        }
      };
    }
  );
angular.module('myApp', ['directives']);

0 个答案:

没有答案