Reputation: 313
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
Upvotes: 4
Views: 5401
Reputation: 5204
You have the wrong syntax. It should be this
.directive('scopeFail', function ($window) {
return {
restrict: 'E',
scope: {
dataSource: '='
},
template: '<div>Value: {{scope.dataSource}}</div>',
link: function (scope, element, attrs) {
console.log('Scope property:', scope.dataSource); //prints Scope property: undefined
}
};
})
The scope properties are passed in as attributes by the attribute name, and you define the data binding as two way, evaluate, or read only.
EDIT
csbarnes answer will also work since dataSource: '='
is just shorthand for dataSource: '=dataSource'
but it makes readability and debugging more difficult IMO. I find it easier to keep the attribute names and scope properties the same. But to each their own.
Upvotes: 0
Reputation: 1893
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.
Upvotes: 11