我们如何将值从一个指令传递到另一个指令模板,并在另一个指令作用域中使用它?

How can we pass the value from directive to directive template and use that in another directive scope

本文关键字:指令 另一个 作用域 一个 我们      更新时间:2023-09-26

我试图将指令属性值传递给模板id,这可以在另一个指令中使用

这是我的index.html

<my-value name="jhon"></my-value>

这是我的js代码

.directive('myValue',function(){
  return {
    restrict:"E",
    templateUrl:"myname.html",
    scope: {
      name:"="
    },
    link:function(scope,element,attr) {
    }
  }
});

这里是我的myname.html

<div>
<p  slide heading="name"></p>
</div>

在上述代码中"slide"是另一个指令

这里是幻灯片指令代码

.directive('slide',function(){
  return{
    restrict:"A",
    link:function(scope,elem,attr){
      console.log(attr.heading);
      // Here i want the name first i assigned in index.html as like    "attr.heading = jhon"
    }
  }
})

我的问题是我将name="jhon"分配给我的值指令,我想动态地将该名称发送给我的值指令模板,从那里我必须将该名称分配给幻灯片指令属性heading= name,这必须在幻灯片指令链接中使用,因为我想将名称动态地从一个指令传递到该指令模板,从那里我必须分配给另一个指令属性,该名称必须在幻灯片指令链接函数中使用

Thanks in advance

        var app = angular.module("my-app",[]);
        app.directive('myValue',function(){
            return {
                restrict:"E",
                template:'<div><p  slide heading="{{name}}"</p></div>',
                scope: {
                    name:"="
                },
                link:function(scope,element,attr) {
                }
            }
        });
        app.directive('slide',function(){
            return{
                restrict:"A",
                link:function(scope,elem,attr){
                    console.log(attr.heading);
                    // Here i want the name first i assigned in index.html as like    "attr.heading = jhon"
                }
            }
        })
        app.controller('demoCtrl',['$scope',function($scope) {
          $scope.myname = "john"
        }]);
<!DOCTYPE html>
<html lang="en" ng-app="my-app">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    
</head>
<body>
   <div ng-controller="demoCtrl">
       <my-value name="myname"></my-value>
   </div>
</body>
</html>

只需更改下面的行。

myname.html

<div>
<p  slide heading="{{name}}"></p>
</div>

index . html

 <my-value name="myname"></my-value>  

在这里指定一些控制器变量,而不是静态名称"john",以便双向数据绑定工作。如

app.controller("...",function($scope){
$scope.myname = "john"
})