gpt4 book ai didi

javascript - 如何使用 $emit 将数据从 Controller 传递到指令

转载 作者:行者123 更新时间:2023-11-29 19:27:10 24 4
gpt4 key购买 nike

我已经成功地将值从 Controller 传递给指令

我的 Controller 中有两个数组

$scope.displayPeople.push(data.userName);
$scope.displayOrg.push(data.orgname);

我需要将这些数据从 Controller 传递给指令

我的指令

<div>

<div class="multitext-wrap blue-border">

<ul inputfocus>

<!--<li class="tag" ng-repeat="list in selecteditemsdisplay track by $index" ng-class="{selected: $index==selectedIndex}" >-->
<!--<span class="tag-label">{{list}}</span><span class="tag-cross pointer" ng-click="Delete($index,selecteditemslist[$index],list,searchid)">x</span>-->
<!--</li>-->

<li class="tag" ng-repeat="list in displayItems track by $index" ng-class="{selected: $index==selectedIndex}" >
<span class="tag-label">{{list}}</span><span class="tag-cross pointer" ng-click="Delete($index,selecteditemslist[$index],list,searchid)">x</span>
</li>

<li class="">
<input type="text" ng-model="searchModel" ng-keydown="selected=false" ng-keyup="searchItem(searchModel,searchobj)"/>


</li>

</ul>
</div>

<div class="typeahead" ng-hide="!searchModel.length || selected">
<div class="typeahead" ng-repeat="item in searchData | filter:searchModel | limitTo:8" ng-click="handleSelection(item,searchobj,$index,searchid)" style="cursor:pointer" ng-class="{active:isCurrent($index)}" ng-mouseenter="setCurrent($index)">
<div class="bs-example">
<div class="list-group list-group-item active">

{{item.displayConfig[0].propertyValue}} {{item.displayConfig[1].propertyValue}}


</div>
</div>


</div>
</div>

</div>

我正在使用 $emit 发送

在 Controller 中

$rootScope.$emit("displayEvent", {displayItems: $scope.displayPeople});


$rootScope.$emit("displayEvent", {displayItems: $scope.displayOrg});

在指令中

$rootScope.$on('displayEvent', function (event, args) {

$scope.displayOrgs = args.displayItems;
console.clear();
console.info($scope.displayOrgs);
});

通过这样做,我得到了重复的组织(无论是人还是组织)

我该如何解决这个问题,请提前感谢我

最佳答案

通过声明“scope: false”,您可以在指令中访问 Controller 的范围。 “false”表示“不创建隔离范围,继承 Controller ”。

.directive('myDirective', function() {
return {
scope: false,
link: function($scope){
//Do stuff with $scope.displayOrgs
//Do stuff with $scope.displayPeople
}
};
});

此选项将创建一个独立的范围并继承选定的变量。这是一种更简洁的方法。

 .directive('myDirective', function() {
return {
scope:{
displayPeople:'=',
displayOrg :'=',
},
link: function($scope){
//Do stuff with $scope.displayOrgs
//Do stuff with $scope.displayPeople
}
};
});

关于javascript - 如何使用 $emit 将数据从 Controller 传递到指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30095420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com