假设我有一个 Controller A:
app.controller('A', function($scope) {
$scope.commonvalue = "";
})
app.directive('dir1', function() {
return {
restrict: 'E',
templateUrl: 'template1.html',
controller: 'A'
};
});
app.directive('dir2', function() {
return {
restrict: 'E',
templateUrl: 'template2.html',
controller: 'A'
};
});
目录1 模板1.html:
<label>Enter value: </label>
<input ng-model="commonvalue"> </input>
目录2 模板2.html:
<p> The value of commonvalue variable is {{ commonvalue }} </p>
我想做的就是更改 dir1 中的 commonvalue 值并在 dir2 中获取它的值。一种解决方案是在 $rootScope 中创建 commonvalue 变量。但我不想那样做。我只想在“A” Controller 范围内更改它。
最佳答案
你可以尝试这样的事情。
<div ng-app="myapp" ng-controller="myCtrl">
<my-changer ng-model="someVal"></my-changer>
<my-receiver ng-model="someVal"></my-receiver>
</div>
angular.module("myapp", [])
.controller("myCtrl", function($scope){
$scope.someVal = "Hello";
}).directive("myChanger", function(){
return {
restrict: "E",
scope: {
txtVal : "=ngModel"
},
template: "<input type='text' ng-model='txtVal'/>",
link: function(scope, elem, attr, ngModelCtrl){
}
};
}).directive("myReceiver", function(){
return {
restrict: "E",
scope: {
txtVal : "=ngModel"
},
template: "<input type='text' ng-model='txtVal'/>",
link: function(scope, elem, attr, ngModelCtrl){
}
}
});
--编辑---
如果您正在寻找一种绑定(bind)方式,请执行此操作。
angular.module("myapp", [])
.controller("myCtrl", function($scope){
$scope.someVal = "Hello";
}).directive("myChanger", function(){
return {
restrict: "E",
scope: {
txtVal : "=ngModel"
},
template: "<input type='text' ng-model='txtVal'/>",
link: function(scope, elem, attr, ngModelCtrl){
}
};
}).directive("myReceiver", function(){
return {
restrict: "E",
scope: {
txtVal : "=ngModel"
},
template: "<p ng-bind='txtVal'/>",
link: function(scope, elem, attr, ngModelCtrl){
}
}
});
关于angularjs - 如何使用两个指令的同一 Controller 将模型变量从一个指令传递到另一个指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495058/