我正在用AngularJS的双向绑定编写isolate scope的指令。 但是,我似乎无法让双向绑定工作。 无论我做什么, isolate scope上的populate属性总是undefined (虽然属性确实存在),而不是它应该被绑定的值。
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 : CodePen链接
那CodePen为什么不显示“Value:Some Data”? 我认为应该发生的是, populate绑定到自定义元素上的data-source的值,该元素是控制器作用域上的data.dataProp ,即Some Data 。
我在哪里出错/如何让隔离范围与data-source属性进行双向绑定?
非常感谢
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
最满意答案
更改populate: '=dataSource'以populate: '=source'或向data-source添加额外的data-属性前缀。 AngularJS自动去除data-属性以允许有效的html5范围属性。
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.
更多推荐
发布评论