angularjs - 如何使用两个指令的同一 Controller 将模型变量从一个指令传递到另一个指令?

标签 angularjs angularjs-directive angularjs-scope

假设我有一个 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){
        }
    }
});

JSFiddle

--编辑---

如果您正在寻找一种绑定(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){
        }
    }
});

Updated JSFiddle

关于angularjs - 如何使用两个指令的同一 Controller 将模型变量从一个指令传递到另一个指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495058/

相关文章:

javascript - AngularJS - 检索评估的属性

javascript - AngularJS 服务无法正常工作

angular - Angular 2.0 中 $scope 的替代品

javascript - 刷新后 Angular $超时

javascript - 如何从 ng-repeat 获得合并结果?

javascript - Angular Modal>Ctrl>Service>Ctrl 继承不起作用

javascript - 观察外部模型的 Angular Directive(指令)

javascript - 使用 OnBeforeUnload 事件刷新浏览器

angularjs - AngularJS UI Typeahead标签和值

javascript - 当客户从另一台计算机(使用 Rails)添加预订时,如何让页面显示预订更新?