简体   繁体   English

单击功能之间的角度共享指令模板

[英]Angular, share directive template between click functions

I have a directive which, when called, passes in a controller and an array . 我有一个指令,该指令在调用时会传入controllerarray

In the controller I pass in, there is an object I want to loop over. 在我传入的控制器中,有一个我想循环播放的对象。

my html looks like this: 我的html看起来像这样:

<div class="row">

    <div class="col-md-6">

        <div class="jumbotron" ng-controller="protocolCtrl as pctrl">

            <button type="button" id="protocol" class="btn btn-primary btn-lg" ng-click="pctrl.getUpdatedList()"
                        data-toggle="modal" data-target="#modal">Modify Current Protocols</button>


            <!--IN THIS MODAL YOU CAN ADD/CHANGE/DELETE DATA-->

            <modal-directive list="pctrl" headers="['ID', 'Protocol']"></modal-directive>

        </div>

    </div>


    <div class="col-md-6">

        <div class="jumbotron" ng-controller="categoryCtrl as cctrl">   
            <button type="button" id="category" class="btn btn-primary btn-lg" ng-click="cctrl.getUpdatedList()"
                        data-toggle="modal" data-target="#modal">Modify Current Categories</button>


            <!--IN THIS MODAL YOU CAN ADD/CHANGE/DELETE DATA-->

            <modal-directive list="cctrl" headers="['ID', 'Category']"></modal-directive>

        </div>

    </div>

</div>

My problem is that no matter what I do, it's always the FIRST directive in the html that showes up, no matter what button I press. 我的问题是,无论我做什么,无论我按什么按钮,它始终都是html中显示的FIRST指令。

My directive looks like this: 我的directive如下所示:

.directive('modalDirective', function(){
    return {
        restrict: 'E',
        templateUrl: '/directives/modal-directive.html',
        scope: {
            list: '=',
            headers: '='
        },
        link: function(scope, element, attrs){

            console.log(attrs.list + ' | ' + attrs.headers);
        }
    };
});

My modal-directive.html looks like this: 我的modal-directive.html看起来像这样:

<table class="table table-striped">
    <thead>

      <tr>
        <th ng-repeat="h in headers"> {{ h }} </th>
      </tr>

    </thead>

    <tbody>

       <!-- Loop through -->

      <tr ng-repeat="l in list.list">

            <!--Access the actual values inside each of the objects in the array-->

            <td ng-repeat="data in l"> {{ data }} </td>

            <td>
                <button type="button" class="btn btn-primary btn-sm"
                     data-toggle="modal">Edit</button>
            </td>

            <td>
                    <button type="button" class="btn btn-danger btn-sm" ng-click="list.removeData(l)"
                        data-dismiss="modal">Remove</button>
            </td>

      </tr>

    </tbody>

</table>

Am I using isolated scopes wrong, or is it something else I need to change in order to make this work? 我使用隔离范围是错误的,还是为了使此功能生效,需要更改其他内容吗?

Update 更新

Here is a fiddle , that demonstrates the problem. 这是一个小提琴 ,演示了问题所在。

No matter which button i click, it displays the same text in the modal body. 无论我单击哪个按钮,它都会在模态主体中显示相同的文本。

Please check this JSFiddle . 请检查此JSFiddle

The reason is that data-target value points to the DOM element id of the modal. 原因是data-target指向模式的DOM元素ID。 If you fixed this id in the directive template, clicking on the button will always initiate the modal with id modal . 如果您在指令模板中固定了此ID,则单击按钮将始终以id modal启动模modal So you need to make the modalId as another parameter of the directive. 因此,您需要将modalId作为指令的另一个参数。


By the way, you can pass a controller to a directive. 顺便说一句,您可以将控制器传递给指令。 Just like this JSFiddle : 就像这样的JSFiddle

angular.module('Joy', [])
    .controller('MyCtrl', ['$scope', function ($scope) {
    this.value = 'Joy';
}])
    .directive('passMeContrller', [function () {
    return {
        restrict: 'A',
        scope: {
            ctrl: '=',
        },
        template: '<div>Value: {{ctrl.value}}</div>'
    };
}]);

The HTML: HTML:

<div ng-app="Joy" ng-controller="MyCtrl as c">
    <div pass-me-contrller ctrl="c"></div>
    <hr>
    <div ng-bind="c.value"></div>
</div>

Because the controller itself is just a JavaScript object. 因为控制器本身只是一个JavaScript对象。

Just a reminder: you are using protocolCtrl as pctrl , so you need to specify like this.list=... . 提醒一下:您正在将protocolCtrl as pctrl ,因此需要指定为this.list=...

If you want to pass in a function to the isolated scope, use & . 如果要将函数传递给隔离的范围,请使用&


However , I suggest not to pass in the whole controller to a directive. 但是 ,我建议不要将整个controller传递给指令。 A controller is designed to: 控制器旨在:

  • Set up the initial state of the $scope object. 设置$ scope对象的初始状态。
  • Add behavior to the $scope object. 将行为添加到$ scope对象。

Controllers are not supposed to be reused. 不应重用控制器。 Usually there are many properties on the $scope , while some of them passed to the directive will not be used by it. 通常$scope上有许多属性,而传递给指令的某些属性将不会被其使用。

You don't really need two controllers and two directives to achieve this. 您实际上并不需要两个控制器和两个指令来实现此目的。 Below is an example of how you can do this. 以下是如何执行此操作的示例。 Notice I moved the controller to the row instead of having separate controllers for each column. 请注意,我将控制器移至该行,而不是为每一列使用单独的控制器。 The controller myCtrl now handles the click functions which are bound to the buttons using the ng-click attribute. 现在,控制器myCtrl处理使用ng-click属性绑定到按钮的单击功能。 This then determines the which text should be placed where by calling there respective functions. 然后,通过调用相应的函数来确定将哪些文本放置在何处。 IE proto() and cat() IE proto()cat()

Now this may not be ideal for your situation depending on how you plan on the architecture of your application. 现在,根据您对应用程序体系结构的计划,这对于您的情况可能并不理想。 But it works for your current problem in terms of what you have provided. 但是,根据您提供的内容,它可以解决当前的问题。

HTML HTML

<body ng-app="TM">
    <div class="row" ng-controller="myCtrl as modalControl">
        <div class="col-md-6">
            <div class="jumbotron" >
                <button 
                    ng-click='proto()'
                    type="button" id="protocol" 
                    class="btn btn-primary btn-lg" 
                    data-toggle="modal" 
                    data-target="#modal">Modify Current Protocols
                </button>
            </div>
        </div>
        <div class="col-md-6">
            <div class="jumbotron">   
                <button
                    ng-click='cat()'
                    type="button" 
                    id="category" 
                    class="btn btn-primary btn-lg" 
                    data-toggle="modal" 
                    data-target="#modal">Modify Current Categories
                </button>
            </div>
        </div>
        <!--IN THIS MODAL YOU CAN ADD/CHANGE/DELETE DATA-->
        <modal-directive ctrl="modalControl"></modal-directive>
    </div>
</body>

Angular JS 角JS

angular.module('TM', [])

.controller('myCtrl', function($scope){

    $scope.text ='default';

    $scope.proto = function() {
        this.text = 'Now looking at the protocol part'
    }
    $scope.cat = function() {
        this.text = 'Now looking at the category part'
    }
})
.directive('modalDirective', function(){
    return {
        restrict: 'E',
        scope: true,       
        template:  ['<div id="modal" class="modal fade" role="dialog">', 
                      '<div class="modal-dialog">',
                        '<div class="modal-content">',
                        '<div class="modal-header">',
                        '<h4 class="modal-title">Modal Header</h4>',
                        '</div>',
                        '<div class="modal-body">',
                        '<p> {{ text }} </p>',
                        '</div>',
                        '<div class="modal-footer">',
                        '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>',
                        '</div>',
                        '</div>', 
                        '</div>',
                        '</div>'].join('')
    }
});

Demo: 演示:

https://jsfiddle.net/DTcHh/10193/ https://jsfiddle.net/DTcHh/10193/

UPDATE: 更新:

Okay, I took another look. 好吧,我又看了一眼。 And even though the above example works. 即使上面的示例可行。 I noticed that I have a few extra things that I didn't necessarily need. 我注意到我还有一些不必要的东西。 For example myCtrl as modalControl doesn't need the as modalControl part. 例如, myCtrl as modalControl不需要as modalControl部分。 Below is an updated example. 下面是一个更新的示例。 I did this one with some different simplified markup. 我使用一些不同的简化标记来完成此操作。

HTML: HTML:

<body ng-app="TestApp">
    <div ng-controller="myCtrl">
        <button ng-click="one()">One</button>
        <button ng-click="two()">Two</button>
        <test-directive></test-directive>
    </div>    
</body>

Angular Example (without Isolated Scope) 角度示例(无孤立范围)

angular.module('TestApp', [])
.controller('myCtrl', function($scope){

    $scope.text ='default';

    $scope.one = function() {
        this.text = 'this is one'
    }
    $scope.two = function() {
        this.text = 'this is two'
    }
})
.directive('testDirective', function(){
    return {
        template: "<div id='test'>{{text}}</div>"  
    }
});

Demo 2: 演示2:

https://jsfiddle.net/krishollenbeck/v8tczaea/12/ https://jsfiddle.net/krishollenbeck/v8tczaea/12/

Note this.. 注意这个..

restrict: 'E',
scope: true

Was also not needed because I am not using Isolated scope in this example. 也不需要,因为在此示例中我没有使用隔离范围。 More info here https://docs.angularjs.org/guide/directive 更多信息在这里https://docs.angularjs.org/guide/directive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM