angularJs 自定义指令传值---父级与子级之间的通信

时间:2023-03-09 01:19:46
angularJs 自定义指令传值---父级与子级之间的通信

angularJs自定义指令用法我忽略,之前有写过,这里只说一下父子级之间如何传值;

例如:

模块我定义为myApp,index.html定义 <my-html bol-val="bolVal"></my-html>,index的controller定义为myAppCtrl;

js:  angular.module('app.myApp')

  .controller('myAppCtrl',['$scope','myService',myAppCtrl])

  .service('myService',function(){

    var obj = {};

    this.setValue = function(key,value){

      obj[key] = value;

    };

    this.getValue = function(key){

      return obj[key];

    };

    this.clearValue = function(key){

      delete obj[key]

    };

  })  //这个比较关键

  .directive('myHtml',function(){

   function myHtmlCtrl($scope,myService){

    //子页面逻辑

    $scope.myFn=function(){

      alert('Hello Word!');

    };//假设有这样一个函数

    (1)父级给子级传过来的值console.log($scope.bolVal);

    (2)子级要传给父级的值,例如要传一个变量$scope.isShow = true,

    则这样设置:myService.setValue('isShow',$scope.isShow)//变量名称可以自己定义,我为了方便还直接取了isShow;

  }

  return {
    restrict: 'E',
    replace: true,
    scope:{
      bolVal:'=' //有时这个值不一定拿得到,是因为嵌套层级太多,需要传过去一个对象才能拿到,看情况而定,如果父级传过来是个函数,那用“&”

    },
    templateUrl:'app/myapp/myhtml.html',//子级html文件所在路径
    controller:['$scope','myService',myHtmlCtrl],
    controllerAs:'vm',
    link: function ($scope,element,attrs) {

      //link函数这里主要进行dom操作

      (1)第一种:可以调用子级的方法。我这里是监听传过来值的变化对这个子页面进行dom操作
      $scope.$watch('bolVal', function (nwVal, odVal) {
        if (nwVal != odVal) {
          $scope.myFn();
        }  
      });

      (2)第二种:可以灵活调用父级方法。

      这里link可以做很多事情,我就不多说了,可以多找几个例子看看!

    }
  };

 });

 index页面controller逻辑

  function myAppCtrl($scope,myService){

    //业务逻辑    

    (1)父传子:

      如果index页面有一个$scope.bolVal = true值;我想要传到子页面myhtml.html中,

      那很简单如上写法页面里定义bol-val="bolVal",切记:遇到大写的一定加“-”并改为小写,

      directive return 对象scope里bolVal:"="

    (2)子传父:

      如果myhtml页面中有一个值想要传到index页面,那就比较复杂,angularJs用法还是比较灵活的,

      可以写一个service服务两个controller中分别注入,例如定义为myService,如上;

      这时,在子页面myhtml的controller里边设置要传的值,在父页面获取传过来的值;

      父页面取值,注意一点:这个值有可能会保存到本地,所以设置之前要先清除:

        myService.clearValue('isShow');

        myService.getValue('isShow');

  }