I have to write a directive that would have the following behavior :
Controller:
vm.mymodel = 'Hello World'
Html:
<custom-input mydirective="{propbind: 'data-value', propmodel: vm.mymodel}"></custom-input>
I would like my custom-input to be transformed as follow:
<custom-input data-value="{{vm.mymodel}}"></custom-input>
- When I update vm.mymodel from the controller, the data-value attribute has to change.
- When I update the data-value, the vm.mymodel has to be updated too.
- I can't use ng-mmodel directive on the custom-input (it uses data-value, and has internal functions applied to it)
So here's what I tried to do :
- In the compile function of my directive, set scope.propbind attribute value to "{{propmodel}}", then remove "mydirective" attribute. But I don't seem to have access to the scope here. However, if I use element.attr('data-value', 'hello world') I can see my data-value correctly set
- I tried to do the same in the link function, but my scope's values are undefined
- I also tried in the controller function, but my scope is also empty, plus I don't have access to attr or element.
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
var vm = this;
this.mymodel = 'Hello world !';
});
app.directive('mydirective', function () {
return {
restrict: 'A',
replace: false,
transclude: false,
scope: {
bindingvalue: '='
},
compile: function(element) {
//remove the element for clarity
element.removeAttr('mydirective');
},
link: function($scope, elem, attr) {
//set the attribute
attr.$set($scope.bindingvalue.propbind, $scope.bindingvalue.propmodel);
//Observe the attribute value for changes
attr.$observe($scope.bindingvalue.propbind, function(value) {
$scope.bindingvalue.propmodel = value;
})
},
controller: function($scope, $element) {
//Nothing here yet
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myctrl as vm">
<input mydirective="{propbind: 'data-value', propmodel: vm.mymodel}" type="text"/>
model value : {{vm.mymodel}}
</div>
Can you please help me ? Is my logic good for my problem ? I think that if I manage to get my scope values in my link function, everythink could work.
Thanks