I am writing a directive with an isolate scope
with a two-way binding in AngularJS
. However, I cannot seem to get the two-way binding to work. No matter what I do, the populate
property on the isolate scope
is always undefined
(although the property does exist) instead of being the value it's supposed to be bound to.
HTML:
<html>
<body ng-app="MyApp">
<div ng-controller="MyController">
{{data.dataProp}} <!-- demonstrates that data.dataProp is defined -->
<scope-fail data-source="data.dataProp"></scope-fail>
</div>
</body>
</html>
JS:
angular.module("MyApp", [])
.controller('MyController', function ($scope) {
$scope.data = {
dataProp: 'Some Data'
}
})
.directive('scopeFail', function ($window) {
return {
restrict: 'E',
scope: {
populate: '=dataSource'
},
template: '<div>Value: {{populate}}</div>',
link: function (scope, element, attrs) {
console.log('Scope property:', scope.populate); //prints Scope property: undefined
}
};
})
CodePen with above code: CodePen link
So why doesn't the CodePen show "Value: Some Data"? What I think is supposed to happen is that populate
binds to the value of data-source
on the custom element which is data.dataProp
on the controller scope which is Some Data
.
Where am I going wrong with this/how can I get the isolate scope to have a two-way binding with the data-source attribute?
Thank you so much
Either change populate: '=dataSource'
to populate: '=source'
or add an extra data-
attribute prefix to data-source
. AngularJS automatically strips the data-
attribute to allow for valid html5 scoped attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With