控制器中的访问值,用于html元素中的ng-if属性

时间:2017-07-07 14:17:35

标签: javascript html angularjs

我有一个现有的模块,我添加了一个指令,它加载一个包含模态窗口的外部文件,我将模态的初始值设置为true:

var application = angular.module('app');
application.directive("history", function () {
    return {
        templateUrl: "dir/dir/dir/file.html"
    };
});
application.controller("factoryController", function ($scope) {
    $scope.ShowModal = true; 
});

在我的HTML中,我有我的模态窗口,我想在控制器中的ShowModal属性为true时创建窗口。如何在HTML中访问该属性?我试过这个:

<div ng-if="ShowModal" id="modal" class="modal" >

但这似乎不起作用。看起来很简单,但我对角度js来说还是比较新的,所以任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

要调用新指令,请创建一个与新指令具有相同标记名称的HTML元素。

命名指令时,必须使用驼峰案例名称myHistory,但在调用它时,必须使用 - 分隔名称,my-history。您可以通过在视图中使用多个方法来调用指令,一个元素是一个。所以试试这个:

<强> JS

 var application = angular.module('app');
    application.directive('modalDialog', function($rootScope) {
    return {
        restrict: 'E',
        scope: {
            show: '=',
            close: '='
        },
        replace: true,
        transclude: true,
        link: function(scope, element, attrs) {
            scope.dialogStyle = {};
            scope.dialogStyle.width = '500px';
            if (attrs.width) scope.dialogStyle.width = attrs.width;
            if (attrs.height) scope.dialogStyle.height = attrs.height;
            if (attrs.header) scope.dialogHeader = attrs.header;
            if (attrs.content) scope.dialogContent = attrs.content;
            if (attrs.closeText) scope.closeText = attrs.closeText;
            scope.hideModal = function() {
                scope.show = false;
            };
            scope.$watch('show',function(value){
                if(value==true){
                    $rootScope.noScroll = true;
                }else{
                    $rootScope.noScroll = false;
                }
            })
        },
        template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><span ng-if='close==true' class='ng-modal-close' ng-click='hideModal()'>X</span><h2 class='ng-modal-header' ng-if='dialogHeader'>{{dialogHeader}}</h2><div class='ng-modal-dialog-content'><p ng-if='dialogContent'>{{dialogContent}}</p><ng-transclude></ng-transclude><button type='button' ng-click='hideModal()' ng-if='closeText'>{{closeText}}</button></div></div></div>"
    }
});
    application.controller("factoryController", function ($scope) {
        $scope.ShowModal = true; 
    });

<强> HTML

<modal-dialog show="ShowModal" ></modal-dialog>

样本使用

<modal-dialog show="fileTypeError" header="Warning" close="true">
    <p>{{fileTypeError}}</p>
    <button type="button" ng-click="closefilePopup()" class="btn_approve1 none">Ok</button>
</modal-dialog>