加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angularjs:使用子指令设置父指令范围值

发布时间:2020-12-17 07:39:53 所属栏目:安全 来源:网络整理
导读:我不知道这是做什么的,但我的目标是: 我有一个父指令 在父指令的块内,我有一个子命令,将从用户那里得到一些输入 子指令将在父指令的范围内设置一个值 我可以从那里拿走 当然,问题是父母指令是兄弟姐妹.所以我不知道该怎么做注意 – 我不想在中设置数据 小提
我不知道这是做什么的,但我的目标是:

>我有一个父指令
>在父指令的块内,我有一个子命令,将从用户那里得到一些输入
>子指令将在父指令的范围内设置一个值
>我可以从那里拿走

当然,问题是父母指令是兄弟姐妹.所以我不知道该怎么做注意 – 我不想在中设置数据

小提琴:http://jsfiddle.net/rrosen326/CZWS4/

HTML:

<div ng-controller="parentController">
    <parent-dir dir-data="display this data">
        <child-dir></child-dir>
    </parent-dir>
</div>

使用Javascript

var testapp = angular.module('testapp',[]);

testapp.controller('parentController',['$scope','$window',function ($scope,$window) {
    console.log('parentController scope id = ',$scope.$id);
    $scope.ctrl_data = "irrelevant ctrl data";
}]);

testapp.directive('parentDir',function factory() {
    return {
        restrict: 'ECA',scope: {
            ctrl_data: '@'
        },template: '<div><b>parentDir scope.dirData:</b> {{dirData}} <div class="offset1" ng-transclude></div> </div>',replace: false,transclude: true,link: function (scope,element,attrs) {
            scope.dirData = attrs.dirData;
            console.log("parent_dir scope: ",scope.$id);
        }
    };
});

testapp.directive('childDir',template: '<h4>Begin child directive</h4><input type="text"  ng-model="dirData" /></br><div><b>childDir scope.dirData:</b> {{dirData}}</div>',transclude: false,attrs) {
            console.log("child_dir scope: ",scope.$id);
            scope.dirData = "No,THIS data!"; // default text
        }
    };
});
如果你想要这种沟通,你需要在child指令中使用require.这将需要父控制器,所以您需要一个控制器,具有您希望儿童指令使用的功能.

例如:

app.directive('parent',function() {
  return {
    restrict: 'E',template: '<div>{{message}}<span ng-transclude></span></div>',controller: function($scope) {
      $scope.message = "Original parent message"

      this.setMessage = function(message) {
        $scope.message = message;
      }
    }
  }
});

控制器在$范围内有一条消息,您有一种方法来更改它.

为什么一个在$范围和一个使用这个?您无法访问子对象中的$scope,因此您需要在函数中使用此函数,以便您的子指令能够调用它.

app.directive('child',function($timeout) {
  return {
    restrict: 'E',require: '^parent',link: function(scope,elem,attrs,parentCtrl) {
      $timeout(function() {
        parentCtrl.setMessage('I am the child!')
      },3000)
    }
  }
})

如您所见,该链接将接收与parentCtrl的第四个参数(或者如果有多个数组).这里我们只需等待3秒钟,直到我们调用我们在父控制器中定义的方法来更改其消息.

看到它住在这里:http://plnkr.co/edit/72PjQSOlckGyUQnH7zOA?p=preview

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读