具有不同消息的相同指令 - angularJS

时间:2016-09-29 10:41:45

标签: javascript angularjs angularjs-directive

我有提交,拒绝和取消等按钮。如果我点击此按钮,会显示带注释的小div,并显示确定和取消按钮。点击ok弹出窗口,弹出“你确定”的消息。

<button type="button" ng-click="showDiv = !showDiv">Submit
</button>
<button type="button" ng-click="showDiv = !showDiv">Reject
</button>

我正在使用像上面提到的小div这样的弹出式模态指令:

<div ng-show="showDiv">
 <yes-no msg="are you sure"></yes-no>
</div>

现在我想在点击每个按钮时更改消息。假如我点击“提交”我的消息应该是'你确定要提交'如果我点击'拒绝',我的消息应该是'你确定拒绝'。

指令:

mainapp.directive('yesNo', function($modal){
    return {
        restrict: 'A',
        scope: {
            msg: '@msg'
        },
        link: linkFn
    };

    function linkFn(scope, element, attrs) {
        var msg = attrs.msg;
        var modalTemplate =  '<div class="modal-content">' +
                        '   <div class="modal-body">' +
                        '       <h4 class="modal-title">' + msg + '</h4>' +
                        '   </div>';
           var modalInstance = $modal.open({
               template: modalTemplate,
               controller: 'yesNoModalCtrl'
           });
       });
    }
});

如何实现这一目标?我将无法在此处发布代码。

2 个答案:

答案 0 :(得分:1)

<input type="button" name="submit" ng-click="buttonclick('are you sure to submit')"/>

<input type="button" name="reject" ng-click="buttonclick('are you sure to reject')"/>

<div ng-show="showDiv">
 <yes-no msg={{message}}></yes-no>
</div>

在您的主控制器中:

app.controller("mainController", function($scope){

$scope.message="";
$scope.buttonclick = function(msg){
   $scope.message= msg;
}
});
app.directive("yesNo", function(){
     return{
     restrict: 'E',
     scope:{
     msg:'@'
    }, 
    link: linkFn,
    controller: 'yesNoModalCtrl'
    }
});

在指令链接功能

function linkFn(scope, element, attrs) {

    attrs.$observe('msg', function(msg) {
        // this function gets triggered each time "msg" is changed
        // You can do whatever you want here
        if (msg) {
            var modalTemplate = '<div class="modal-content">' +
                '   <div class="modal-body">' +
                '       <h4 class="modal-title">' + msg + '</h4>' +
                '   </div>';
            var modalInstance = $modal.open({
                template: modalTemplate,
                controller: 'yesNoModalCtrl'
            });
        }

    });
} 

plunker

答案 1 :(得分:0)

创建控制器功能:

$scope.showModal = function(msg) {
    $scope.showDiv = !$scope.showDiv;
    $scope.msg = msg;
}

在你的按钮中:

<button type="button" ng-click="showModal('Are you sure')">Submit
</button>
<button type="button" ng-click="showModal('Some other text')">Reject
</button>

<div ng-show="showDiv">
    <yes-no msg="msg"></yes-no>
</div>