Dynamic ng-model binding inside a directive

2019-02-06 03:07发布

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!

1条回答
Root(大扎)
2楼-- · 2019-02-06 03:52

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>',            
        };
    });
查看更多
登录 后发表回答