Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic ng-model binding inside a directive

I'm trying to create a custom component that uses a dynamic ng-model inside-out the directive.

As an example, I could invoke different components like:

<custom-dir ng-model="domainModel1"></custom-dir>
<custom-dir ng-model="domainModel2"></custom-dir>

With a directive like:

app.directive('customDir', function() {
  return {
    restrict: 'EA',
    require: '^ngModel',
    scope: {
      ngModel: '=dirValue',
    },
    template: '<input ng-model="dirValue" />',
    link: function(scope, element, attrs, ctrl) {
      scope.dirValue = 'New';
    }
  };
});

The idea is that the textbox from the directive would change if the model changes, and in the other way around.

The thing is that I've tried different approaches with no success at all, you can check one of this here: http://plnkr.co/edit/7MzDJsP8ZJ59nASjz31g?p=preview In this example, I'm expecting to have the value 'New' in both of the inputs, since I'm changing the model from the directive and is a bi-directional bound (=). But somehow is not bound in the right way. :(

I will be really grateful if someone give some light on that. Thanks in advance!

like image 317
DreaMTT Avatar asked Dec 19 '13 01:12

DreaMTT


People also ask

What is difference between ng-model and Ng bind directive?

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

Is NG-model a directive?

ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form.

Can we use NG-model for Div?

NgModel expects the bound element to have a value property, which div s don't have. That's why you get the No value accessor error. I don't know if the input event is supported on all browsers for contenteditable . You could always bind to some keyboard event instead.

What is the use of NG-model directive?

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.


1 Answers

Something like this?

http://jsfiddle.net/bateast/RJmhB/1/

HTML:

<body ng-app="test">
    <my-dir ng-model="test"></my-dir>
    <input type="text" ng-model="test"/>
</body>

JS:

angular.module('test', [])
    .directive('myDir', function() {
        return {
            restrict: 'E',
            scope: {
                ngModel: '='
            },
            template: '<div><input type="text" ng-model="ngModel"></div>',            
        };
    });
like image 71
Banana-In-Black Avatar answered Sep 20 '22 21:09

Banana-In-Black