gpt4 book ai didi

javascript - 如何仅对 Angular 中的某些变量使用父范围,并保持其他变量隔离

转载 作者:行者123 更新时间:2023-11-29 15:33:59 26 4
gpt4 key购买 nike

mydirective 是一个独立的作用域指令。这是因为我不想将指令的所有逻辑暴露给指令之外的任何地方。但是我想在指令之外访问输入数据。

<div mydirective>
<input ng-model="data.input">
</div>

<div mydirective>
<input ng-model="otherdata.public">
<input ng-model="more.than.one">
</div>

{{data.input}}
{{otherdata.public}}

我更喜欢 HTML 无需更改就可以工作,并且只更改指令代码。所以我想知道如何创建指令

app.directive('mydirective',function(){ return {
scope:true,
controller:function($scope){
$scope.this_variable_needs_to_be_private=true
},
transclude:true
}})

编辑:添加 transclude:true。但我仍然没有答案。

最佳答案

考虑使用 $transclude使用 $scope.$new() 创建您自己的 childScope 函数:

(function() {
"use strict";

angular.module("myApp", [])
.controller("Controller1", ['$scope', Controller1])
.directive("mydirective", [mydirective]);

function Controller1($scope) {
$scope.data = {
input: 'data.input'
};
$scope.otherdata = {
public: 'otherdata.public'
};
$scope.more = {
than: {
one: 'more.than.one'
}
}
}

function mydirective() {
function _link($scope, $element, $attrs, controller, $transclude) {
var childScope = $scope.$new(); //create a childScope

//$scope.this_variable_needs_to_be_private = true; //<-- doing this would add it to public parent scope
childScope.this_variable_needs_to_be_private = true; //<-- this puts it only on this directive's childscope

// See: https://docs.angularjs.org/api/ng/service/$compile#transclusion
$transclude(childScope, function(clone, scope) { //transcluding with our childScope
$element.append(clone); //appending the clone of our content;
});
}

return {
transclude: true,
link: _link
};
}

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Controller1">

<div mydirective>
<input ng-model="data.input">
<br /><strong>this_variable_needs_to_be_private:</strong> {{this_variable_needs_to_be_private}}
</div>

<br />

<div mydirective>
<input ng-model="otherdata.public">
<input ng-model="more.than.one">
<br /><strong>this_variable_needs_to_be_private:</strong> {{this_variable_needs_to_be_private}}
</div>

<hr />
<strong>data.input:</strong> {{data.input}}
<br /><strong>otherdata.public:</strong> {{otherdata.public}}
<br /><strong>this_variable_needs_to_be_private:</strong> {{this_variable_needs_to_be_private}}


</div>

进一步阅读 $transclude:https://stackoverflow.com/a/13184889/446030 .

关于javascript - 如何仅对 Angular 中的某些变量使用父范围,并保持其他变量隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31559007/

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