如何在angularjs中访问一个指令作用域值到另一个指令

How to access one directive scope value to other directive in angularjs?

本文关键字:指令 一个 作用域 另一个 angularjs 访问      更新时间:2024-02-27

实际上,我的要求是将一个指令的作用域获取到另一个指令,并需要执行双向绑定。

每当ng模型发生更改时,我都需要更改JSON值。在下面的示例中,JSON具有带属性的行集。我必须将这些属性名称与控件(文本框)绑定,如ng model=CuId。因此,每当相应的属性值发生变化时,JSON都需要更新。

源代码:

var app = angular.module("myApp", []);
app.directive("main", function() {
});
app.directive("sub1", function() {
    return {
        restrict: 'E',
        replace: true,
        template : "<h1>sub1</h1>",
        link: function($scope, element, attrs) {
           $scope.soJSON={
                "entityinfo": {
                  "entity": "Customer29Jan16",
                  "tenantId": "292FEC76-5F1C-486F-85A5-09D88096F098",
                  "timeStamp": "2016-04-07T10:33:38.507Z"
                },
                "collections": {
                  "Customer29Jan16": {
                    "meta": {
                      "parentreference": "***",
                      "pkname": "***",
                      "fkname": "***"
                    },
                    "rowset": [
                      {
                        "CuId": "test",
                        "Name": "test",
                        "Quantity": "test"                       
                      }
                    ],
                    "rowfilter": []
                  }
                }
              }
        }
    };
});
app.directive("sub2", function() {
    return {
        template : "<input ng-model=CuId> <input ng-model=Name> <input ng-model=Quantity>"
    };
});

HTML代码:

<div ng-app="myApp">
<main>
   <sub1>Test<</sub1>
   <sub2>Test<</sub2>
</main>
</div>

JS Fiddle链接:https://jsfiddle.net/bagya1985/23vz1xux/1/

Well AngularJS支持指令控制器,这些控制器在需要相同控制器的多个指令之间共享。您需要在子指令中使用require:'^main'。有关详细信息,您可以查看链接https://docs.angularjs.org/guide/directive