在angularjs中添加html元素时,如何运行代码?

在angularjs中添加html元素时,如何运行代码?,angularjs,Angularjs,我有一个指令,用ng if添加html元素, 我想在每次添加元素时调用回调: html模板: <div ng-if="showUserConsent()" class="userConsent"> <div class="userConsent-topBar"></div> </div> 我想在包含内部div后运行一些代码,建议?Angular可以在创建ng应用程序、创建模块、引用控制器和创建服务时执行代码。据我所知,它不支持div的o

我有一个指令,用ng if添加html元素, 我想在每次添加元素时调用回调:

html模板:

<div ng-if="showUserConsent()" class="userConsent">
    <div class="userConsent-topBar"></div>
</div> 

我想在包含内部div后运行一些代码,建议?

Angular可以在创建ng应用程序、创建模块、引用控制器和创建服务时执行代码。据我所知,它不支持div的onShow类型功能。有几种方法可以实现相同的功能,但如果不了解更多,我无法推荐“最佳”功能。以下是几个选项:

选项1:在控制器上创建一个名为isFirstTime的变量,并将其设置为false。然后在showUserApprovement()中,检查HasseenApprovement消息是否为false,isFirstTime是否为false,然后运行代码

function($scope, $userConsentService){
    this.userConsentService = $userConsentService;
    this.scope = $scope;
    this.isFirstTime = false;
    this.scope.showUserConsent = function(){
        if(!this.userConsentService.HasSeenConsentMessage && !this.isFirstTime){
            //run code
            this.isFirstTime = true;
        }
        return !this.userConsentService.HasSeenConsentMessage;
    } 
}
选项2:用于监视对此.UserApproverService.HasseenApproverMessage的更改

function($scope, $userConsentService){
    this.userConsentService = $userConsentService;
    this.scope = $scope;
    this.isFirstTime = false;
    this.scope.showUserConsent = function(){
        return !this.userConsentService.HasSeenConsentMessage;
    };

    $scope.$watch('this.userConsentService.HasSeenConsentMessage', function(newValue, oldValue){
        if(newValue !== oldValue){
            //execute code here!
        }
    }
}

是否有理由不希望将其作为ShowUserApprove()的一部分运行?ShowUserApprove实际上应该是shouldShowUserApprove,这意味着它在每个摘要中被调用多次。我希望实现一个“onShow()”,它发生在以下答案解决您的问题后?如果是,请将其标记为答案/投票表决答案。如果没有,请让我知道我能提供什么帮助。
function($scope, $userConsentService){
    this.userConsentService = $userConsentService;
    this.scope = $scope;
    this.isFirstTime = false;
    this.scope.showUserConsent = function(){
        return !this.userConsentService.HasSeenConsentMessage;
    };

    $scope.$watch('this.userConsentService.HasSeenConsentMessage', function(newValue, oldValue){
        if(newValue !== oldValue){
            //execute code here!
        }
    }
}