在《AngularJS权威教程》中,自定义指令和DOM双向数据绑定有一个在线demo,网址:http://jsbin.com/IteNita/1/edit?html,js,output,具体代码如下:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
</head>
<body> <label>Their URL field:</label>
<input type="text" ng-model="theirUrl">
<div my-directive
some-attr="theirUrl"
my-link-text="Click me to go to Google"></div> <script>
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'A',
replace: true,
scope: {
myUrl: '=someAttr',
myLinkText: '@'
},
template: '\
<div>\
<label>My Url Field:</label>\
<input type="text" ng-model="myUrl" />\
<a href="{{myUrl}}">{{myLinkText}}</a>\
</div>\
'
}
})
</script> </body>
</html>
其中myUrl: '=someAttr'我不是很理解,于是改成 myUrl: '@someAttr',但是这样页面显示如图:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdoAAABzCAIAAACw4lRqAAAJxklEQVR4nO3dPW67wBaHYXZEk+1QZTUUWcnNlZCushOq9P82iaJIKbkFBubjnGH4MgfnfeQisTEMHvPz5DAxRQf8Aa+vr//w79/r6+vZXQFVcXYDgHsgjnvEsWXEMf6EVwzO7gqoiGMAMIE4BgATiGMAMIE4BgATiGMAMIE4BgATiGMAMIE4BgATiGMAMIE4PsF//vs/ble8nf3GwYMjjk/AgX1F9BqORhyfgAP7iug1HI04PgEH9hXRazhabhy3dVkUZd0u3sDqJ95BW5dFURRFUTXZ7ZxZrqn61SVxYF8RvYajTXHcVIWsrNu7xXFTSQu3delkXNxQL/6yN+gnJ3GMNHoNR5NGx376OfcdP8jNjuOpef0QN/g9N1fnglN5GnH8B9FrONr14zh8mDjGIeg1HG1pHDuVgiCTxkKs/5AXX7ewuq1ESK31cTw+KyeOg3pH1QhPy9mfYLnh9bk1rqniV6nrOg7sa6LXcLRFcezEYBA1Xkjpv9xiMD24XBzHG4rAWo0jc3+ClyF4kYjjh0Kv4WjL4ti5042lKAGdVI3jOB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if+lDOqDmTOcpLmo0lQwaWy1LI6HrafnHd8ME4fDOV55RW3npNln3cajyDVTmNe1JF5e2KIzS1oYTac3582w/tWKFdHLcpd5x6voE9weGv8kfUX02nLZ/45xfXerEWs2x/FM2fhhcWBfUdxr0hlzbtxyb/u+PzfG8R8dGnfE8TXRa7PGonnXdbP/yXJtzZc76g+qw6dYHcerv9/tQXBgXxG9liHrKykeg3/C4MwyRc/s189bx4F9RfQaLCOOVzr9isjc1t3OfuMAKuIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEwgjgHABOIYAEz4P8PmhNvx1WhHAAAAAElFTkSuQmCC" alt="" />
查看元素发现链接的href="theirUrl",并且;两个输入框的内容也不同步,仔细查看代码,发现DOM中将some-attr设置值方式不是表达式,所以修改如下(修改处为绿色):
<body> <label>Their URL field:</label>
<input type="text" ng-model="theirUrl">
<div my-directive
some-attr={{theirUrl}}
my-link-text="Click me to go to Google"></div> <script>
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'A',
replace: true,
scope: {
myUrl: '@someAttr',
myLinkText: '@'
},
template: '\
<div>\
<label>My Url Field:</label>\
<input type="text" ng-model="myUrl" />\
<a href="{{myUrl}}">{{myLinkText}}</a>\
</div>\
'
}
})
</script> </body>
效果是,第2个输入框随着第1个变化,反之不是。
总结:指令要访问其内部的指令,需要:
1.指令属性值用表达式即{{}}设置,改为“”
2.内部指令对应属性数据绑定”@”改为”=”