当前位置:Gxlcms > JavaScript > 详解AngularJS1.x学习directive 中‘& ’‘=’ ‘@’符号的区别使用

详解AngularJS1.x学习directive 中‘& ’‘=’ ‘@’符号的区别使用

时间:2021-07-01 10:21:17 帮助过:55人阅读

对于一个Html5框架的好坏,我们有几个评判标准, 轻量级,可拓展,易复用,速度快。

对组件复用这点,angular以directive的形式展示给开发者,是一个还算不错的选择,作为一个UI组件,必定存在数据交互。

那么数据交互过程中的几个符号我们一定要有所了解,以及他们的区别是什么,防止我们在运用过程中出错。

1. 首先,我们看一scope作用域下面@的使用:

html

  1. <!doctype html>
  2. <html ng-app='myApp'>
  3. <head>
  4. </head>
  5. <body>
  6. <div ng-controller="listCtrl">
  7. <input type="text" ng-model="t" />
  8. <test title="{{t}}" >
  9. <span>我的angularjs</span>
  10. </test>
  11. </div>
  12. <script type="text/javascript" src="angular.js"></script>
  13. <script type="text/javascript" src="main.js"></script>
  14. </body></html>

js

  1. var myApp=angular.module('myApp',[]);
  2. myApp.controller('listCtrl',function($scope){
  3. $scope.logchore="motorola";
  4. });
  5. myApp.directive('test',function(){
  6. return {
  7. 'restrict':'E',
  8. scope:{
  9. title:"@"
  10. },
  11. template:'<div >{{title}}</div>'
  12. }
  13. });

这个必须指定的,这里的title是指令里scope的@对应的,t就是控制域scope下的 .

2. = 的使用。

html

  1. <!doctype html>
  2. <html ng-app='myApp'>
  3. <head>
  4. </head>
  5. <body>
  6. <div ng-controller="listCtrl">
  7. <input type="text" ng-model="t" />
  8. <test title="t" >
  9. <p>{{title}}</p>
  10. <span>我的angularjs</span>
  11. </test>
  12. </div>
  13. <script type="text/javascript" src="angular.js"></script>
  14. <script type="text/javascript" src="main05.js"></script>
  15. </body></html>

js

  1. var myApp=angular.module('myApp',[]);
  2. myApp.controller('listCtrl',function($scope){
  3. $scope.logchore="motorola";
  4. });
  5. myApp.directive('test',function(){
  6. return {
  7. 'restrict':'E',
  8. scope:{
  9. title:"="
  10. },
  11. template:'<div >{{title}}</div>'
  12. }
  13. });

和上面@相比,这个直接赋值等于scope域下的t了

3. 最好我们看看&符号的使用

html

  1. <!doctype html>
  2. <html ng-app='myApp'>
  3. <head>
  4. </head>
  5. <body>
  6. <div ng-controller="listCtrl">
  7. <test flavor="logchore()" ></test>
  8. </div>
  9. <script type="text/javascript" src="angular.js"></script>
  10. <script type="text/javascript" src="main05.js"></script>
  11. </body></html>

js

  1. var myApp=angular.module('myApp',[]);
  2. myApp.controller('listCtrl',function($scope){
  3. $scope.logchore=function(){
  4. alert('ok');
  5. };
  6. });
  7. myApp.directive('test',function(){
  8. return {
  9. 'restrict':'E',
  10. scope:{
  11. flavor:"&"
  12. },
  13. template:'<div ><button ng-click="flavor()"></button></div>'
  14. }
  15. });

尝试一下,就明白了,简洁明了!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行