gpt4 book ai didi

javascript - 在 Angular 中,如何将指令的 Controller 共享给其子内容(当 transinclude 为 true 时)?

转载 作者:行者123 更新时间:2023-12-03 06:47:11 25 4
gpt4 key购买 nike

我尝试搜索有关 SO 的引用资料。但对答案不满意。我是 Angular 的新手。我试图通过创建这样的指令来实现嵌入:

app.directive('wrapperDirective',function(){        
return{
restrict :'E',
controller:'wrapperCtrl',
template :'<div class="widget-template" ng-transclude></div>',
transclude: true,
replace:true,
scope:{
cityList : '='
}
}
});

app.controller('wrapperCtrl', ['$scope',function($scope, $rootScope){
$scope.citynames = $scope.cityList;
});




<wrapper-directive cityList="Bangalore">
<div>{{ citynames }}</div>
</wrapper-directive>

现在如何使数据可用,声明为子内容的属性。我真的很困惑,请帮忙。

最佳答案

当你使用作用域和指令时要小心,因为 Controller 可以有自己的作用域,所以你可能会混淆。

另一种方法是使用 Controller 作为语法。只需在 Controller 中声明如下:

function myController($scope) {
var vm = this;
vm.yourAttribute = value;
}

就像您可以使用访问 Controller 属性

 wrapperCtrl.yourAttribute

如果编写 wrapperCtrl.yourAttributes 太长,您可以使用属性 Controller ,如下所示

app.directive('wrapperDirective',function(){        
return{
restrict :'E',
controller:'wrapperCtrl',
controllerAs: 'yourname',
template :'<div class="widget-template" ng-transclude></div>',
transclude: true,
replace:true,
scope:{
cityList : '='
}
}


});

仅当您想要访问属性时才执行yourname.yourAttribute

关于javascript - 在 Angular 中,如何将指令的 Controller 共享给其子内容(当 transinclude 为 true 时)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37683409/

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