AngularJS: Modifying an item in a repeating directive

This is just the directive html so please see the article about Repeating directives for the rest of the code. To modify an item on the fly as the directive is being built you can do it in the Post-compile function as follows:

This is the longer way:

myApp.directive("searchResult3",function(){
    return{
        templateUrl: '/directives/searchresult.html'
        , replace: true      
                           
        , scope:
        {
              personObject: "="  
        }
        , compile: function(elem, attrs){
            
            console.log('Compiling...'); 
            console.log(elem.html);
            //elem.removeAttr('class'); // I can remove a class here
            return{
                pre: function(scope,elements,attrs){
                    console.log('Pre-linking...');
                    console.log(elements);
                    //NOT safe to change item here. You can leave this pre section out
                },
                
                post: function(scope,elements, attrs){ //scope = model, elements = view
                    console.log('Post-linking...');
                    console.log(scope);
                    console.log(elements);
                    
                    //I could also change an item in the loop here.
                    if(scope.personObject.name === 'Jane Doe')
                    {
                        elements.removeAttr('style');
                    }
                }
                
            };
        }
        
    }
});

This is the short-hand:

myApp.directive("searchResult3",function(){
    return{
        templateUrl: '/directives/searchresult.html'
        , replace: true      
                           
        , scope:
        {
              personObject: "="  
        }
        ,   
        link: function(scope,elements, attrs){ //scope = model, elements = view
                    console.log('Post-linking...');
                    console.log(scope);
                    console.log(elements);
                    
                    //I could also change an item in the loop here.
                    if(scope.personObject.name === 'Jane Doe')
                    {
                        elements.removeAttr('style');
                    }
                }
        
    }
});


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s