Dynamic ng-model binding inside a directive

橙三吉。 提交于 2019-12-18 12:57:06

问题


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:


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>',            
        };
    });


来源:https://stackoverflow.com/questions/20672098/dynamic-ng-model-binding-inside-a-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!