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。