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

时间:2015-03-09 16:28:03

标签: angularjs

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

html模板:

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

控制器:

function ($scope, $userConsentService) {                

        this.userConsentService = $userConsentService;
        this.scope = $scope;  
        this.scope.showUserConsent = () => { return this.showUserConsent() };            

  }

    private showUserConsent(): boolean {
        return !this.userConsentService.HasSeenConsentMessage;
    }

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

1 个答案:

答案 0 :(得分:0)

Angular有一种在创建ng-app,创建模块,引用控制器以及创建服务时执行代码的方法。据我所知,它不支持div的onShow类型函数。有几种方法可以实现相同的功能,但不知道更多我不能推荐&#34;最好的&#34;一。以下是几个选项:

选项1:在控制器上创建名为isFirstTime的变量并将其设置为false。然后在showUserConsent()中,检查HasSeenConsentMessage是否为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:使用$watch监控对this.userConsentService.HasSeenConsentMessage的更改。

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!
        }
    }
}