angular 指令学习

在指令中scope 定义的值的用法:例如

  scope: {
     local: "@nameprop",
     secondLocal:"@secondNameprop",
     secondLocalTest:"@threeNameprop"
    }

local,secondLocal,secondLocalTest这三个值只能在指令内使用。而nameprop,secondNameprop,threeNameprop作为指令属性在指令上使用。

@属性是单向传,即上级向指令传

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>指令学习</title>
    <script src="https://cdn.bootcss.com/angular.js/1.7.0/angular.min.js"></script>
    
</head>

<body ng-app='app'>
    <div ng-controller="myController">
     <div ng-click="topClick('test')">我是父类</div>
     <input type="text" ng-model="myaddress"/>
     <hr>
     {{myaddress}}aaa
     <hr>
     ccc
     <hr>
     <my-directive  my-data="myaddress" my-click="otherClick('other-bbb')"></my-directive>
    </div>
</body>
<script type="text/javascript">
  var app = angular.module('app', []);
    app.directive('myDirective',myDirective);
    function myDirective(){
      var directive={
          restrict:'AE',
          template:"<div ng-click='sonClick(1111)'>点击我</div><div>{{innerData}}</div>",
          scope:{
            selectData:"&myClick",
            innerData:"=myData"//myData作为指令属性使用这里且是共享的,可以双向改变
          },
          link:function(scope,ele,attr){
            scope.sonClick=function(aaa){
              scope.innerData=aaa; // innerData只在指令内部使用
              scope.selectData();
            
            }
          }
       }
       return directive;
    };
    app.controller("myController",["$scope",function($scope){
        $scope.topClick = function(aa){
            alert(aa);
        }
        $scope.otherClick = function(aa){
            alert(aa);
        }
        $scope.myaddress="广州"; //初始化数据
    }])
  </script>
</html>

 效果图

 

 点击后

 

 修改输入框数据

 

posted @ 2022-10-31 22:54  剧里局外  阅读(15)  评论(0编辑  收藏  举报