AngularJS:指令隔离范围未定义 [英] AngularJS : Directive Isolated Scope Undefined
问题描述
我正在用 AngularJS
中的双向绑定编写一个带有 isolate 作用域
的指令.但是,我似乎无法使双向绑定起作用.无论我做什么,isolate 作用域
上的 populate
属性总是 undefined
(尽管该属性确实存在)而不是它的值应该是绑定的.
HTML:
<body ng-app="MyApp"><div ng-controller="MyController">{{data.dataProp}} <!-- 演示定义了 data.dataProp --><scope-fail data-source="data.dataProp"></scope-fail>
</html>
JS:
angular.module("MyApp", []).controller('MyController', function ($scope) {$scope.data = {dataProp: '一些数据'}}).directive('scopeFail', function ($window) {返回 {限制:'E',范围: {填充:'=数据源'},模板:'<div>值:{{populate}}</div>',链接:函数(范围、元素、属性){console.log('Scope 属性:', scope.populate);//打印范围属性:未定义}};})
带有上述代码的 CodePen:CodePen 链接
那么为什么 CodePen 不显示值:一些数据"?我认为应该发生的是 populate
绑定到自定义元素上的 data-source
值,该元素是 data.dataProp
上的控制器范围是 Some Data
.
我哪里出错了/如何让隔离作用域与数据源属性进行双向绑定?
非常感谢
将 populate: '=dataSource'
更改为 populate: '=source'
或添加额外的data-
属性前缀到 data-source
.AngularJS 会自动去除 data-
属性以允许有效的 html5 范围属性.
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.
这篇关于AngularJS:指令隔离范围未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!