代码:
<!DOCTYPE html> <html ng-app="MyModule"> <head> <Meta charset="utf-8"> <title>Scope作用域测试</title> <script src="../Script/angular.min.js"></script> <style type="text/css"> .frame { text-align:center; padding: 2px 8px; margin: 0px; font-size: 20px; width: 500px; background-color: #eee; } .tip { font-size: 20px; color: #666; margin: 3px 0px; padding: 5px 0px; } </style> <script type="text/ng-template" id="tpl"> <div class="tip"> <span>姓名:{{textName}}</span> <span>年龄:{{textAge}}</span> </div> <button ng-transclude></button> </script> </head> <body> <div class="frame" ng-controller="MyScope" style="text-align: center;"> 姓名:<input ng-model="text_name" placeholder="请输入姓名" /><br /> 年龄:<input ng-model="text_age" placeholder="请输入年龄" /> <div class="tip">{{tip}}</div> <ts-json a-attr="{{text_name}}" b-attr="text_age" reset="reSet()">重置</ts-json> </div> <script type="text/javascript"> var app = angular.module('MyModule',[]) .controller('MyScope',function ($scope) { $scope.reSet = function () { $scope.tip = "姓名与年龄重置成功!"; } }) .directive('tsJson',function () { return { restrict: 'EAC',templateUrl: 'tpl',transclude: true,scope: { textName: '@aAttr',textAge: '=bAttr',reSet: '&reset' },link: function (scope,iEle,iAttrs) { iEle.bind('click',function () { scope.$apply(function () { scope.reSet(); scope.textName = '海哥'; scope.textAge = '20'; }) }) } }; }); </script> </body> </html>
截图: