AngularJS ng-include和AngularJS自定义指令不愿一起工作。

3

我有一个AngularJS应用程序,我使用登录框作为弹出框。现在,所有登录框的HTML代码都与主HTML代码一起加载(工作正常),但我的目标是在单击登录按钮时获取登录框HTML(以保存用户资源)。我尝试使用ng-include实现它。它可以正常工作,但只能使用一次。如果我尝试在关闭登录框后再次点击登录按钮,什么也不会发生。

首先,我尝试使用此函数绑定href以在按下登录按钮时包含HTML:

$scope.toggleLogInForm = function(){

    if(typeof $scope.htmlTemplates.LoginPopupHtml === 'undefined'){
        $scope.htmlTemplates.LoginPopupHtml =  urlSer.url+'html/getLoginPopupHtml';
    }

    $scope.showLogin = true;
    console.log($scope.showLogin); // print true when press login button
}

使用带有ng-include属性的元素来存储HTML。

<div ng-include src="htmlTemplates.LoginPopupHtml"></div>

控制隐藏/显示登录框的指令:

webApp.directive('regmodal', function () {
return {
  template: '<div class="modal fade">' + 
      '<div class="modal-dialog">' + 
        '<div class="">' + 
          '<div class="" ng-transclude></div>' + 
        '</div>' + 
      '</div>' + 
    '</div>',
  restrict: 'E',
  transclude: true,
  replace:true,
  scope:true,
  link: function postLink(scope, element, attrs) {
    scope.title = attrs.title;
    scope.$watch(attrs.visible, function(value){
      if(value == true)
        $(element).modal('show');
      else
        $(element).modal('hide');
    });

    $(element).on('shown.bs.modal', function(){
      scope.$apply(function(){
        scope.$parent[attrs.visible] = true;
      });
    });

    $(element).on('hidden.bs.modal', function(){
      scope.$apply(function(){
        scope.$parent[attrs.visible] = false;
      });
    });
  }
};
});

最后是我的HTML登录页面代码:
<regmodal  class="form-login-heading" title="Registration" visible="showLogin">     
        <form class="form-login geform" ng-submit="login()">
        ... // skiped not important for example
        </form>
</regmodal>   
1个回答

3

您需要在控制器中使用watch函数。

mymodal.controller('MainCtrl', function ($scope) {
    $scope.modalObj = { showModal : false };
    $scope.toggleModal = function(){
        $scope.modalObj.showModal = !$scope.modalObj.showModal;
    };
  });

在指令中
scope.$watch(function () { return scope.modalObj.showModal; }, function(value){
    if(value == true)
      $(element).modal('show');
    else
      $(element).modal('hide');
});

请查看这个链接: angularjs - ng-include中自定义指令无法工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接