gpt4 book ai didi

javascript - 使用替换时, Angular 隔离范围值在模板中不可见

转载 作者:行者123 更新时间:2023-11-30 00:04:16 25 4
gpt4 key购买 nike

我正在创建一个小应用程序,我在模板中有以下指令。

smallgrid.directive.js:

angular.module('myActions')
.directive('smallgrid', ['$rootScope', function($rootScope) {
return {
restrict: "E",
scope: {
actionable: "="
},
controller: function($scope) {
$scope.setLocation = function() {
console.log("yee");
};
}
};
}])
.directive('three', function() {
return {
replace: true,
templateUrl: '/app/my_actions/directives/templates/grid3x3.template.html'
};
})
.directive('four', function() {
return {
replace: true,
templateUrl: '/app/my_actions/directives/templates/grid4x4.template.html'
};
})
.directive('five', function() {
return {
replace: true,
templateUrl: '/app/my_actions/directives/templates/grid5x5.template.html'
};
});

grid3x3.template.html

<div class="k-edit-field" id="board">
<div class="row" ng-click="setLocation()">
{{actionable.probability}}
</div>
</div>

我按如下方式使用该指令:

<smallgrid three actionable="currentAction.actionable" ng-if="somecondition"></smallgrid>

UI 正确呈现。但是它显示 {{actionable.probability}} 是空的并且没有触发 Click 事件。但是,如果我删除隔离范围并直接访问变量,则值可用。我知道当我在 three 指令中使用隔离作用域时,我无法访问 smallgrid 的值。有没有办法将这些值从 smallgrid 传递到模板?

最佳答案

将指令作为指令的属性传递肯定会遇到范围问题。

如果使用 ng-transclude 对嵌套指令使用作用域继承,效果会更好。 .

所以你的出发点应该是

<smallgrid actionable="currentAction.actionable" ng-if="somecondition">
<three></three>
</smallgrid>

这边<three>可以访问 $parent

function smallgrid() {
return {
restrict: "E",
transclude: true,
scope: {
actionable: "="
},
template: `<div ng-transclude></div>`,
controller: function($scope) {
$scope.setLocation = function() {
console.log("yee");
};
}
};
}
function three() {
return {
template: `<div class="k-edit-field" id="board">
<div class="row" ng-click="$parent.setLocation()">
test = {{$parent.actionable.probability}}
</div>
</div>`
};
}
function myController($scope) {
$scope.currentAction = {actionable: {probability: "test"}};
$scope.somecondition = true;
}
angular.module('myApp', []);
angular
.module('myApp')
.controller('myController', myController)
.directive('smallgrid', smallgrid)
.directive('three', three);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myController">
<smallgrid actionable="currentAction.actionable" ng-if="somecondition">
<three></three>
</smallgrid>
</div>
</div>

关于javascript - 使用替换时, Angular 隔离范围值在模板中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39115413/

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