\n",h=!0)}g=h?'\n":""}return g=a.hosts?''+a.host+"\n"+g:""===g?null:g}p("htmlTemplate");var z,A=i,B=r("jobs")+f.id+"/job_events/",C=j,D=C.inject(A,{mode:"edit"});A.base=d.path(),D.job_id=f.id,c.flashMessage=null,D.selected=[],D.expand=!0,D.parentNode="parent-event",D.childNode="child-event",D.removeSetHostLinks&&D.removeSetHostLinks(),D.removeSetHostLinks=D.$on("SetHostLinks",function(a,b){for(var c=0;c15?5:e,$('textarea[name="'+c+'"]').attr("rows",e)));break;case"module_name":case"module_args":a.event_data.res&&a.event_data.res.invocation&&(t[c]=a.event_data.res.invocation.fld)
+}q("stop")}).error(function(a){k(t,a,status,null,{hdr:"Error!",msg:"Failed to retrieve host: "+f.event_id+". GET status: "+status})}),t.navigateBack=function(){var a="/jobs/"+f.job_id+"/job_events";f.page&&(a+="?page="+f.page),d.url(a)},t.rawView=function(){p({event_id:t.id})}}function JobHostSummaryList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){o("htmlTemplate");var u=h,v=c.path().replace(/^\//,"").split("/")[0],w=q(v)+e.id+"/job_host_summaries/",x=i,y=x.inject(u,{mode:"edit"});u.index="hosts"===v?!1:!0,y.selected=[],"hosts"===v?(y.job_id=null,y.host_id=e.id):(y.job_id=e.id,y.host_id=null),y.RemoveSetHostLink&&y.RemoveSetHostLink(),y.RemoveSetHostLink=y.$on("setHostLink",function(a,b){for(var c=0;c0?y.jobhosts[0].summary_fields.host.name:"Host"}),e.inventory&&y.$emit("setHostLink",e.inventory))}),l({scope:y,set:"jobhosts",list:u,url:w}),m({scope:y,list:u,url:w}),e.host_name&&(y[u.iterator+"SearchField"]="host",y[u.iterator+"SearchValue"]=e.host_name,y[u.iterator+"SearchFieldLabel"]=u.fields.host.label),y.search(u.iterator),y.showEvents=function(a,b){f.setUrl(b),f.get().success(function(b){j({path:"/jobs/"+b.id,title:b.name}),c.url("/jobs/"+b.id+"/job_events/?host="+encodeURI(a))}).error(function(a,c){p(y,a,c,null,{hdr:"Error!",msg:"Failed to lookup last job: "+b+". GET status: "+c})})},y.showJob=function(a){c.path("/jobs/"+a)},y.refresh=function(){null===y.host_id&&(y.jobSearchSpin=!0,y.jobLoading=!0,t("start"),r({scope:y,set:"jobhosts",iterator:"jobhost",url:y.current_url}))}}function JobTemplatesList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){o("htmlTemplate");var y=h,z=q("job_templates"),A=i,B=c.path().replace(/^\//,"").split("/")[0],C="job_templates"===B?"edit":"select",D=A.inject(y,{mode:C});b.flashMessage=null,D.removePostRefresh&&D.removePostRefresh(),D.removePostRefresh=D.$on("PostRefresh",function(){w("stop"),$("#prompt-modal").off()}),l({scope:D,set:"job_templates",list:y,url:z}),m({scope:D,list:y,url:z}),e.name&&(D[y.iterator+"SearchField"]="name",D[y.iterator+"SearchValue"]=e.name,D[y.iterator+"SearchFieldLabel"]=y.fields.name.label),D.search(y.iterator),j(),D.showActivity=function(){x({scope:D})},D.addJobTemplate=function(){c.path(c.path()+"/add")},D.editJobTemplate=function(a){c.path(c.path()+"/"+a)},D.deleteJobTemplate=function(a,b){var c=function(){$("#prompt-modal").on("hidden.bs.modal",function(){w("start")}),$("#prompt-modal").modal("hide");var b=z+a+"/";f.setUrl(b),f.destroy().success(function(){D.search(y.iterator)}).error(function(a){w("stop"),p(D,a,status,null,{hdr:"Error!",msg:"Call to "+b+" failed. DELETE returned status: "+status})})};k({hdr:"Delete",body:"Are you sure you want to delete "+b+"?",action:c})},D.submitJob=function(a){v({scope:D,id:a})}}function JobTemplatesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w){n("htmlTemplate");var x,y,z=o("job_templates"),A=g,B=h,C=B.inject(A,{mode:"add",related:!1}),D={},E={};C.parseType="yaml",u(C),C.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],C.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],C.playbook_options=[],C.allow_callbacks="false",B.reset(),l(),t({scope:C,master:D,check_field:"allow_callbacks",default_val:!1}),s({scope:C,form:A,current_item:null,list:p,field:"inventory"}),jQuery.extend(!0,E,q),E.name="cloudcredentials",E.iterator="cloudcredential",s({url:o("credentials")+"?cloud=true",scope:C,form:A,current_item:null,list:E,field:"cloud_credential",hdr:"Select Cloud Credential"}),s({url:o("credentials")+"?kind=ssh",scope:C,form:A,current_item:null,list:q,field:"credential",hdr:"Select Machine Credential"}),x=function(a,b){var c;a!==b&&C.project&&(v("start"),c=o("projects")+C.project+"/playbooks/",i.setUrl(c),i.get().success(function(a){var b,c=[];for(b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}b&&j("Waning",b,"alert-info")}).error(function(a,b){k(C,a,b,A,{hdr:"Error!",msg:"Failed to get project "+C.project+". GET returned status: "+b})}))},C.selectPlaybookUnregister&&C.selectPlaybookUnregister(),C.selectPlaybookUnregister=C.$watch("project_name",function(a,b){x(a,b),y(a,b)}),s({scope:C,form:A,current_item:null,list:r,field:"project"}),C.formSave=function(){B.clearApiErrors(),v("start");var a,b,c={};try{if(a="json"===C.parseType?JSON.parse(C.variables):jsyaml.load(C.variables),"object"!=typeof a)throw"failed to return an object!";for(b in A.fields)"select"===A.fields[b].type&&"playbook"!==b?c[b]=C[b].value:"variables"!==b&&(c[b]=C[b]);c.extra_vars=JSON.stringify(a,void 0," "),w(c.extra_vars)&&(c.extra_vars=""),i.setUrl(z),i.post(c).success(function(){v("stop");var a=d.path().replace(/^\//,"").split("/")[0];"job_templates"===a&&m(),m(1)}).error(function(a,b){v("stop"),k(C,a,b,A,{hdr:"Error!",msg:"Failed to add new job template. POST returned status: "+b})})}catch(e){v("stop"),j("Error","Error parsing extra variables. Parser returned: "+e)}},C.formReset=function(){B.reset();for(var a in D)C[a]=D[a]}}function JobTemplatesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D){p("htmlTemplate");var E,F,G=v("job_templates"),H=h,I=g,J=H.inject(I,{mode:"edit",related:!0}),K=0,L=d.path().replace(/^\//,"").split("/")[0],M={},N=f.id,O={};J.parseType="yaml",x(J),J.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],J.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],J.playbook_options=null,J.playbook=null,H.reset(),F=function(a){var b;C(a)||(b=v("projects")+a+"/playbooks/",A("start"),i.setUrl(b),i.get().success(function(a){var b;for(J.playbook_options=[],b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}A("stop"),b&&j("Waning",b,"alert-info")}).error(function(a,b){k(J,a,b,I,{hdr:"Error!",msg:"Failed to get project "+J.project+". GET returned status: "+b})}))},J.watchProjectUnregister&&J.watchProjectUnregister(),J.watchProjectUnregister=J.$watch("project_name",function(a,b){a!==b&&""!==b&&null!==b&&void 0!==b&&(J.playbook=null,F(J.project),E())}),J.removeJobTemplateLoadFinished&&J.removeJobTemplateLoadFinished(),J.removeJobTemplateLoadFinished=J.$on("jobTemplateLoadFinished",function(){if(K++,K>=2)for(var a in O)J.search(O[a].iterator)}),J.removeRelatedJobs&&J.removeRelatedJobs(),J.removeRelatedJobs=J.$on("relatedjobs",function(){var a,b;if(J.jobs&&J.jobs.length)for(a=0;a0)for(c=0;c/g," ");for(y in z.fields.status.searchOptions)if(z.fields.status.searchOptions[y].value===e.status){C[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[y];break}}C.search(z.iterator),j(),C.refresh=function(){x("start"),C.jobLoading=!1,u({scope:C,set:"jobs",iterator:"job",url:C.current_url})},C.refreshJob=C.refresh,C.editJob=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a)},C.viewEvents=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_events")},C.viewSummary=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_host_summaries")},C.deleteJob=function(a){f.setUrl(A+a+"/"),f.get().success(function(b){var c,d,e,g;"pending"===b.status||"running"===b.status||"waiting"===b.status?(d=b.related.cancel,e="cancel",g="Cancel Job"):(d=A+a+"/",e="delete",g="Delete Job"),c=function(){f.setUrl(d),"cancel"===e?f.post().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. POST returned status: "+b})}):f.destroy().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. DELETE returned status: "+b})})},k({hdr:g,body:"Are you sure you want to "+e+" job "+a+"?",action:c})}).error(function(a,b){p(C,a,b,null,{hdr:"Error!",msg:"Failed to get job details. GET returned status: "+b})})},C.submitJob=function(a,b){s({scope:C,id:a,template:b})}}function JobsEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){function A(a){if(null!==a&&""!==a&&void 0!==a){var b=v("projects")+a+"/playbooks/";i.setUrl(b),i.get().success(function(a){F.playbook_options=[];for(var b=0;b15?15:c}p("htmlTemplate");var C=v("jobs"),D=h,E=g,F=D.inject(E,{mode:"edit",related:!0}),G={},H=f.id,I={},J=0;D.reset(),F.job_id=H,F.parseType="yaml",F.statusSearchSpin=!1,F.jobLoadedRemove&&F.jobLoadedRemove(),F.jobLoadedRemove=F.$on("jobLoaded",function(a,b){A(F.project),F[E.name+"ReadOnly"]="new"===F.status?!1:!0,$("#forks-slider").slider("option","value",F.forks),$("#forks-slider").slider("disable"),$('input[type="checkbox"]').attr("disabled","disabled"),$('input[type="radio"]').attr("disabled","disabled"),$("#host_config_key-gen-btn").attr("disabled","disabled"),$("textarea").attr("readonly","readonly"),i.setUrl(F.template_url),i.get().success(function(a){var b=a.host_config_key?"true":"false";F.host_config_key=a.host_config_key,w({scope:F,master:G,check_field:"allow_callbacks",default_val:b}),F.callback_url=a.related?a.related.callback:"<< Job template not found >>",F.$emit("jobTemplateLoadFinished")}).error(function(){z("stop"),F.callback_url="<< Job template not found >>"}),b?(i.setUrl(b),i.get().success(function(a){F.cloud_credential_name=a.name,F.$emit("jobTemplateLoadFinished")}).error(function(a,b){k(F,a,b,null,{hdr:"Error!",msg:"Failed to related cloud credential. GET returned status: "+b})})):F.$emit("jobTemplateLoadFinished")}),F.removeJobTemplateLoadFinished&&F.removeJobTemplateLoadFinished(),F.removeJobTemplateLoadFinished=F.$on("jobTemplateLoadFinished",function(){J++,J>=3&&z("stop")}),F.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],F.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],F.playbook_options=null,F.playbook=null,z("start"),i.setUrl(C+":id/"),i.get({params:{id:H}}).success(function(a){var b,c,d,e,f,g;l();for(d in E.fields){if("variables"!==d&&null!==a[d]&&void 0!==a[d]){if("select"===E.fields[d].type)if(F[d+"_options"]&&F[d+"_options"].length>0)for(b=0;b/g," ");for(a in A.fields.scm_type.searchOptions)if(A.fields.scm_type.searchOptions[a].value===e.scm_type){F[A.iterator+"SearchSelectValue"]=A.fields.scm_type.searchOptions[a];break}}else if(e.status){F[A.iterator+"SearchValue"]=e.status,F[A.iterator+"SearchField"]="status",F[A.iterator+"SelectShow"]=!0,F[A.iterator+"SearchFieldLabel"]=A.fields.status.label,F[A.iterator+"SearchSelectOpts"]=A.fields.status.searchOptions;for(a in A.fields.status.searchOptions)if(A.fields.status.searchOptions[a].value===e.status){F[A.iterator+"SearchSelectValue"]=A.fields.status.searchOptions[a];break}}F.search(A.iterator)}),F.removeChoicesReady&&F.removeChoicesReady(),F.removeChoicesReady=F.$on("choicesReadyProject",function(){H++,2===H&&F.$emit("choicesCompleteProject")}),y({scope:F,url:B,field:"status",variable:"project_status_options",callback:"choicesReadyProject"}),y({scope:F,url:B,field:"scm_type",variable:"project_scm_type_options",callback:"choicesReadyProject"}),j(),F.showActivity=function(){x({scope:F})},F.addProject=function(){c.path(c.path()+"/add")},F.editProject=function(a){c.path(c.path()+"/"+a)},F.showSCMStatus=function(a){var b,c=F.$on("PostRefresh",function(){var d;
+for(b=0;bRefresh button to view the latest status.","alert-info")}).error(function(a,b){p(F,a,b,null,{hdr:"Error!",msg:"Call to "+c+" failed. GET status: "+b})})}),F.cancelUpdate=function(a,b){var c,d,e=!1;for(c=0;cRefresh button to view the latet status.","alert-info")},F.refresh=function(){w("start"),F.projectLoading=!1,v({scope:F,set:"projects",iterator:"project",url:F.current_url})},F.SCMUpdate=function(a){var b;for(b=0;bb;b++){for(d[b].match(/[A-Z]/g)?(""!==R&&R+1==b&&(y++,C++),R=b,o++):d[b].match(/[a-z]/g)?(""!==S&&S+1==b&&(z++,C++),S=b,p++):d[b].match(/[0-9]/g)?(b>0&&e-1>b&&s++,""!==T&&T+1==b&&(A++,C++),T=b,q++):d[b].match(/[^a-zA-Z0-9_]/g)&&(b>0&&e-1>b&&s++,""!==U&&U+1==b&&(B++,C++),U=b,r++),f=!1,g=0;e>g;g++)d[b]==d[g]&&b!=g&&(f=!0,x+=Math.abs(e/(g-b)));f&&(w++,v=e-w,x=Math.ceil(v?x/v:x))}for(h=0;23>h;h++)i=ib.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(D++,G++);for(h=0;8>h;h++)i=jb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(E++,G++);for(h=0;8>h;h++)i=kb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(F++,G++);o>0&&n>o&&(nScore=parseInt(nScore+2*(n-o)),V="+ "+parseInt(2*(n-o))),p>0&&n>p&&(nScore=parseInt(nScore+2*(n-p)),W="+ "+parseInt(2*(n-p))),q>0&&n>q&&(nScore=parseInt(nScore+q*P),X="+ "+parseInt(q*P)),r>0&&(nScore=parseInt(nScore+r*Q),Y="+ "+parseInt(r*Q)),s>0&&(nScore=parseInt(nScore+s*H),Z="+ "+parseInt(s*H)),(p>0||o>0)&&0===r&&0===q&&(nScore=parseInt(nScore-n),t=n,_="- "+n),0===p&&0===o&&0===r&&q>0&&(nScore=parseInt(nScore-n),u=n,ab="- "+n),w>0&&(nScore=parseInt(nScore-x),bb="- "+x),y>0&&(nScore=parseInt(nScore-y*I),cb="- "+parseInt(y*I)),z>0&&(nScore=parseInt(nScore-z*J),db="- "+parseInt(z*J)),A>0&&(nScore=parseInt(nScore-A*K),eb="- "+parseInt(A*K)),D>0&&(nScore=parseInt(nScore-D*L),fb="- "+parseInt(D*L)),E>0&&(nScore=parseInt(nScore-E*M),gb="- "+parseInt(E*M)),F>0&&(nScore=parseInt(nScore-F*N),hb="- "+parseInt(F*N)),nScore>100?nScore=100:0>nScore&&(nScore=0),k=$("#progbar"),l=$AnsibleConfig.password_strength,m=$AnsibleConfig.password_strength-15<0?0:$AnsibleConfig.password_strength-15,k.css("width",nScore+"%"),nScore>=0&&m>=nScore?(lb="Weak",k.addClass("progress-bar-danger"),k.removeClass("progress-bar-success progress-bar-warning")):nScore>m&&l>=nScore?(lb="Good",k.addClass("progress-bar-warning"),k.removeClass("progress-bar-success progress-bar-danger")):nScore>l&&(lb="Strong",k.addClass("progress-bar-success"),k.removeClass("progress-bar-warning progress-bar-danger"))}else k=$("#progbar"),k.css("width","0%"),k.removeClass("progress-bar-success progress-bar-warning");return nScore}function AdminsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){var q=h,r=o("organizations")+e.organization_id+"/users/",s=i,t="select",u=s.inject(h,{mode:t}),v=o("organizations")+e.organization_id+"/admins/";p({scope:u,list:q,url:v,returnToCaller:1}),l({scope:u,set:"admins",list:q,url:r}),m({scope:u,list:q,url:r}),u.search(q.iterator),j()}function Authenticate(a,b,c,d,e,f,g,h,i,j,k){var l,m,n,o;l=function(){$("#login-username").focus()},n=k(d.sessionExpired)?a.get("sessionExpired"):d.sessionExpired,m=function(){return k(d.lastPath)?a.get("lastPath"):d.lastPath},$AnsibleConfig.debug_mode&&console&&(console.log("User session expired: "+n),console.log("Last URL: "+m())),$(".modal[aria-hidden=false]").each(function(){"login-modal"!==$(this).attr("id")&&$(this).modal("hide")}),i("stop"),$("#login-modal").modal({show:!0,keyboard:!1,backdrop:"static"}),$("#login-modal").on("shown.bs.modal",function(){l()}),o=angular.element(document.getElementById("login-modal")).scope(),o.login_username=null,o.login_password=null,o.loginForm.login_username.$setPristine(),o.loginForm.login_password.$setPristine(),"/logout"===e.path()&&f.logout(),d.userLoggedIn=!1,a.put("userLoggedIn",!1),$("#login-password").bind("keypress",function(a){var b=a.keyCode?a.keyCode:a.which;13===b&&$("#login-button").click()}),o.reset=function(){$("#login-form input").each(function(){$(this).val("")})},o.systemLogin=function(a,b){$(".api-error").empty();var c;k(a)||k(b)?h("Error!","Please provide a username and password before attempting to login.","alert-danger",l):(i("start"),f.retrieveToken(a,b).success(function(a,b){$("#login-modal").modal("hide"),c=a.token,f.setToken(a.token,a.expires),d.sessionTimer=j.init(),f.getUser().success(function(a){f.setUserInfo(a),d.user_is_superuser=a.results[0].is_superuser,f.getLicense().success(function(a){f.setLicense(a.license_info),m()?e.path(m()):e.url("/home?login=true")}).error(function(){i("stop"),h("Error","Failed to access user information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){i("stop"),h("Error","Failed to access license information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){var c,d,e;if(i("stop"),a.non_field_errors&&0===a.non_field_errors.length)for(e in a)o[e+"Error"]=a[e][0];else a.non_field_errors&&a.non_field_errors.length>0?(c="Error",d=a.non_field_errors[0]):(c="Error",d="The login attempt failed with a status of: "+b),o.reset(),h(c,d,"alert-danger",l)}))}}function CredentialsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){o("htmlTemplate"),t("start");var v,w=h,x=q("credentials"),y=i,z=c.path().replace(/^\//,"").split("/")[0],A="credentials"===z?"edit":"select",B=y.inject(w,{mode:A});B.selected=[],B.credentialLoading=!0,v=q(z)+("users"===z?e.user_id+"/credentials/":e.team_id+"/credentials/"),r({scope:B,list:w,url:v,returnToCaller:1}),B.removePostRefresh&&B.removePostRefresh(),B.removePostRefresh=B.$on("PostRefresh",function(){var a,b;for(t("stop"),$("#prompt-modal").off(),w.fields.kind.searchOptions=B.credential_kind_options,a=0;a/g," ");for(x in z.fields.status.searchOptions)if(z.fields.status.searchOptions[x].value===b.status){B[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[x];break}}if(b.source){B[z.iterator+"SearchField"]="source",B[z.iterator+"SelectShow"]=!0,B[z.iterator+"SearchSelectOpts"]=z.fields.source.searchOptions,B[z.iterator+"SearchFieldLabel"]=z.fields.source.label.replace(/ /g," ");for(x in z.fields.source.searchOptions)if(z.fields.source.searchOptions[x].value===b.source){B[z.iterator+"SearchSelectValue"]=z.fields.source.searchOptions[x];break}b.status&&(B[z.iterator+"ExtraParms"]="&inventory_source__status__icontains="+b.status)}b.has_external_source&&(B[z.iterator+"SearchField"]="has_external_source",B[z.iterator+"SearchValue"]=z.fields.has_external_source.searchValue,B[z.iterator+"InputDisable"]=!0,B[z.iterator+"SearchType"]="in",B[z.iterator+"SearchFieldLabel"]=z.fields.has_external_source.label),B.search(z.iterator),f(),B.showActivity=function(){p({scope:B})},B.editGroup=function(a,b){q({scope:B,group_id:a,inventory_id:b,groups_reload:!1})},B.viewUpdateStatus=function(a){B.groups=B.home_groups,o({scope:B,tree_id:a})},B.updateGroup=function(a){var b=w({list:B.home_groups,key:"id",val:a});b&&(u(b.source)||("updating"===b.status?s("Update in Progress","The inventory update process is currently running for group "+b.name+". Use the Refresh button to monitor the status.","alert-info"):(r("start"),t.setUrl(b.related.inventory_source),t.get().success(function(a){v({scope:B,url:a.related.update,group_name:a.summary_fields.group.name,group_source:a.source,tree_id:b.id,group_id:b.id})}).error(function(a,c){e(B,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+b.related.inventory_source+" POST returned status: "+c})}))))},B.refresh=function(){B.search(z.iterator,null,!1,!0)}}function HomeHosts(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){h("htmlTemplate");var s=d,t=c,u=i("hosts"),v=s.inject(t,{mode:"edit"});v.removePostRefresh&&v.removePostRefresh(),v.removePostRefresh=v.$on("PostRefresh",function(){for(var a=0;a0?(z.inventories[a].failed_hosts_tip=z.inventories[a].hosts_with_active_failures+(1===z.inventories[a].hosts_with_active_failures?" host":" hosts")+" with job failures. Click to view details.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="true"):0===z.inventories[a].total_hosts?(z.inventories[a].failed_hosts_tip="No hosts defined. Click to add.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="na"):(z.inventories[a].failed_hosts_tip=z.inventories[a].total_hosts+(z.inventories[a].total_hosts>1?" hosts":" host")+" with no job failures. Click to view details.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="false"),z.inventories[a].status=z.inventories[a].inventory_sources_with_failures+" / "+z.inventories[a].total_inventory_sources,z.inventories[a].inventory_sources_with_failures>0?(z.inventories[a].status_tip=z.inventories[a].inventory_sources_with_failures+" cloud "+(1===z.inventories[a].inventory_sources_with_failures?"source":"sources")+" with failures. Click to view details.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="failed"):0===z.inventories[a].total_inventory_sources?(z.inventories[a].status_tip="Not synced with a cloud source. Click to edit.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="na"):(z.inventories[a].status_tip=z.inventories[a].total_inventory_sources+" cloud "+(z.inventories[a].total_inventory_sources>1?"sources":"source")+" with no failures. Click to view details.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="successful")}),z.removeRefreshInventories&&z.removeRefreshInventories(),z.removeRefreshInventories=z.$on("RefreshInventories",function(){z.search(u.iterator)}),z.showActivity=function(){s({scope:z})},z.editInventoryProperties=function(a){t({scope:z,inventory_id:a})},z.addInventory=function(){c.path(c.path()+"/add")},z.editInventory=function(a){c.path(c.path()+"/"+a)},z.deleteInventory=function(a,b){var c=function(){var b=v+a+"/";$("#prompt-modal").on("hidden.bs.modal",function(){r("start")}),$("#prompt-modal").modal("hide"),f.setUrl(b),f.destroy().success(function(){z.search(u.iterator)}).error(function(a,c){r("stop"),p(z,a,c,null,{hdr:"Error!",msg:"Call to "+b+" failed. DELETE returned status: "+c})})};k({hdr:"Delete",body:"Are you sure you want to delete "+b+"?",action:c})},z.lookupOrganization=function(a){f.setUrl(q("organizations")+a+"/"),f.get().success(function(a){return a.name})},z.viewJobs=function(a){c.url("/jobs/?inventory__int="+a)},z.viewFailedJobs=function(a){c.url("/jobs/?inventory__int="+a+"&status=failed")}}function InventoriesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v){n("htmlTemplate");var w,x=t("inventory"),y=g,z=h;y.well=!0,y.formLabelSize=null,y.formFieldSize=null,w=z.inject(y,{mode:"add",related:!1}),w.inventoryParseType="yaml",z.reset(),l(),u(w,"inventory_variables","inventoryParseType"),s({scope:w,form:y,current_item:f.organization_id?f.organization_id:null,list:p,field:"organization"}),w.formSave=function(){z.clearApiErrors(),v("start");try{var a,b,c;if(b="json"===w.inventoryParseType?JSON.parse(w.inventory_variables):jsyaml.load(w.inventory_variables),"object"!=typeof b)throw"failed to return an object!";c={};for(a in y.fields)"inventory_variables"!==a&&(y.fields[a].realName?c[y.fields[a].realName]=w[a]:c[a]=w[a]);i.setUrl(x),i.post(c).success(function(a){var c=a.id;w.inventory_variables?(i.setUrl(a.related.variable_data),i.put(b).success(function(){v("stop"),d.path("/inventories/"+c+"/")}).error(function(a,b){v("stop"),k(w,a,b,null,{hdr:"Error!",msg:"Failed to add inventory varaibles. PUT returned status: "+b})})):(v("stop"),d.path("/inventories/"+c+"/"))}).error(function(a,b){v("stop"),k(w,a,b,y,{hdr:"Error!",msg:"Failed to add new inventory. Post returned status: "+b})})}catch(e){v("stop"),j("Error","Error parsing inventory variables. Parser returned: "+e)}},w.formReset=function(){z.reset()}}function InventoriesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P){f("htmlTemplate");var Q=e,R=g;a.inventory_id=c.inventory_id,r({path:b.path(),title:"{{ inventory_name }}"}),a.removeGroupTreeLoaded&&a.removeGroupTreeLoaded(),a.removeGroupTreeLoaded=a.$on("GroupTreeLoaded",function(b,c,e){var f,g;f=angular.element(document.getElementById("breadcrumbs")),f.html(q({list:R,mode:"edit"})),d(f)(a),Q.inject(R,{mode:"edit",id:"groups-container",breadCrumbs:!1,searchSize:"col-lg-5 col-md-5 col-sm-5"}),a.groups=e,a.inventory_name=c,a.groups.length>0?(a.selected_tree_id=a.groups[0].id,a.selected_group_id=a.groups[0].group_id,a.groups[0].selected_class="selected",a.groups[0].active_class="active-row",a.selected_group_name=a.groups[0].name):(a.selected_tree_id=null,a.selected_group_id=null),a.show_failures=!1,l({scope:a,inventory_id:a.inventory_id,tree_id:a.selected_tree_id,group_id:a.selected_group_id}),setTimeout(function(){$("#groups_table .name-column").each(function(){var a,b,c,d,e;a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%",$(this).find(".group-name").css({width:e})}),L("#groups_table .group-name a"),L("#hosts_table .host-name a")},2500),M(),g=P("inventoryAutoHelp"),"off"!==g&&a.autoShowGroupHelp&&a.showGroupHelp({autoShow:!0})}),a.removeGroupTreeRefreshed&&a.removeGroupTreeRefreshed(),a.removeGroupTreeRefreshed=a.$on("GroupTreeRefreshed",function(){setTimeout(function(){L("#groups_table .group-name a")},2500),a.showHosts(a.selected_tree_id,a.selected_group_id,!1)}),a.removeGroupDeleteCompleted&&a.removeGroupDeleteCompleted(),a.removeGroupDeleteCompleted=a.$on("GroupDeleteCompleted",function(){a.selected_tree_id=1,a.selected_group_id=null,i({scope:a,inventory_id:a.inventory_id,refresh:!0})}),a.removeCopMoveGroup&&a.removeCopyMoveGroup(),a.removeCopyMoveGroup=a.$on("CopyMoveGroup",function(b,c,d){G({scope:a,target_tree_id:d,inbound_tree_id:c})}),a.removeCopMoveHost&&a.removeCopyMoveHost(),a.removeCopyMoveHost=a.$on("CopyMoveHost",function(b,c,d){H({scope:a,target_tree_id:c,host_id:d})}),a.showHosts=function(b,c,d){if(null!==b){j("start"),a.selected_tree_id=b,a.selected_group_id=c,a.hosts=[],a.show_failures=d;for(var e=0;e"+c.name+". Use the Refresh button to monitor the status.","alert-info"):(j("start"),t.setUrl(c.related.inventory_source),t.get().success(function(b){v({scope:a,url:b.related.update,group_name:b.summary_fields.group.name,group_source:b.source,tree_id:c.id,group_id:c.group_id})}).error(function(b,d){j("stop"),u(a,b,d,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+c.related.inventory_source+" POST returned status: "+d})}))))},a.cancelUpdate=function(b){z({scope:a,tree_id:b})},a.toggle=function(b){x({scope:a,list:R,id:b})},a.refreshGroups=function(b,c){b&&(a.selected_tree_id=b,a.selected_group_id=c),i({scope:a,inventory_id:a.inventory_id,refresh:!0})},a.viewUpdateStatus=function(b,c){y({scope:a,tree_id:b,group_id:c})},a.deleteGroup=function(b,c){p({scope:a,tree_id:b,group_id:c,inventory_id:a.inventory_id})},a.createHost=function(){B({scope:a})},a.editInventoryProperties=function(){C({scope:a,inventory_id:a.inventory_id})},a.editHost=function(b){D({scope:a,host_id:b,inventory_id:a.inventory_id})},a.deleteHost=function(b,c){E({scope:a,host_id:b,host_name:c})},a.toggleHostEnabled=function(b,c){F({scope:a,host_id:b,external_source:c})},a.showGroupActivity=function(){var b,c,d;a.selected_group_id?(d=A({list:a.groups,key:"id",val:a.selected_tree_id}),b=J("activity_stream")+"?group__id="+a.selected_group_id,c="Showing all activities for group "+d.name):(c="Showing all activities for all "+a.inventory_name+" groups",b=J("activity_stream")+"?group__inventory__id="+a.inventory_id),I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showHostActivity=function(){var b,c;c="Showing all activities for all "+a.inventory_name+" hosts",b=J("activity_stream")+"?host__inventory__id="+a.inventory_id,I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showJobSummary=function(a){K({job_id:a})},a.showGroupHelp=function(a){var b={defn:O};a&&(b.autoShow=a.autoShow||!1),N(b)},i({scope:a,inventory_id:a.inventory_id,refresh:!1})}function JobEventsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){function y(a){var b,c,d,e,f,g="",h=!1;if(a.res){if("string"==typeof a.res)c=a.res.match(/\n/g),d=c?c.length:1,d=d>10?10:d,h=!0,g+='
\n',g+="\n",g+='\n",g+="
\n";else for(e in a.res){if(("msg"===e||"stdout"===e||"stderr"===e)&&null!==a.res[e]&&""!==a.res[e]){switch(g+='
\n",h=!0)}g=h?'\n":""}return g=a.hosts?''+a.host+"\n"+g:""===g?null:g}p("htmlTemplate");var z,A=i,B=r("jobs")+f.id+"/job_events/",C=j,D=C.inject(A,{mode:"edit"});A.base=d.path(),D.job_id=f.id,c.flashMessage=null,D.selected=[],D.expand=!0,D.parentNode="parent-event",D.childNode="child-event",D.removeSetHostLinks&&D.removeSetHostLinks(),D.removeSetHostLinks=D.$on("SetHostLinks",function(a,b){for(var c=0;c15?5:e,$('textarea[name="'+c+'"]').attr("rows",e)));break;case"module_name":case"module_args":a.event_data.res&&a.event_data.res.invocation&&(t[c]=a.event_data.res.invocation.fld)}q("stop")}).error(function(a){k(t,a,status,null,{hdr:"Error!",msg:"Failed to retrieve host: "+f.event_id+". GET status: "+status})}),t.navigateBack=function(){var a="/jobs/"+f.job_id+"/job_events";f.page&&(a+="?page="+f.page),d.url(a)},t.rawView=function(){p({event_id:t.id})}}function JobHostSummaryList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){o("htmlTemplate");var u=h,v=c.path().replace(/^\//,"").split("/")[0],w=q(v)+e.id+"/job_host_summaries/",x=i,y=x.inject(u,{mode:"edit"});u.index="hosts"===v?!1:!0,y.selected=[],"hosts"===v?(y.job_id=null,y.host_id=e.id):(y.job_id=e.id,y.host_id=null),y.RemoveSetHostLink&&y.RemoveSetHostLink(),y.RemoveSetHostLink=y.$on("setHostLink",function(a,b){for(var c=0;c0?y.jobhosts[0].summary_fields.host.name:"Host"}),e.inventory&&y.$emit("setHostLink",e.inventory))}),l({scope:y,set:"jobhosts",list:u,url:w}),m({scope:y,list:u,url:w}),e.host_name&&(y[u.iterator+"SearchField"]="host",y[u.iterator+"SearchValue"]=e.host_name,y[u.iterator+"SearchFieldLabel"]=u.fields.host.label),y.search(u.iterator),y.showEvents=function(a,b){f.setUrl(b),f.get().success(function(b){j({path:"/jobs/"+b.id,title:b.name}),c.url("/jobs/"+b.id+"/job_events/?host="+encodeURI(a))}).error(function(a,c){p(y,a,c,null,{hdr:"Error!",msg:"Failed to lookup last job: "+b+". GET status: "+c})})},y.showJob=function(a){c.path("/jobs/"+a)},y.refresh=function(){null===y.host_id&&(y.jobSearchSpin=!0,y.jobLoading=!0,t("start"),r({scope:y,set:"jobhosts",iterator:"jobhost",url:y.current_url}))}}function JobTemplatesList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){o("htmlTemplate");var y=h,z=q("job_templates"),A=i,B=c.path().replace(/^\//,"").split("/")[0],C="job_templates"===B?"edit":"select",D=A.inject(y,{mode:C});b.flashMessage=null,D.removePostRefresh&&D.removePostRefresh(),D.removePostRefresh=D.$on("PostRefresh",function(){w("stop"),$("#prompt-modal").off()}),l({scope:D,set:"job_templates",list:y,url:z}),m({scope:D,list:y,url:z}),e.name&&(D[y.iterator+"SearchField"]="name",D[y.iterator+"SearchValue"]=e.name,D[y.iterator+"SearchFieldLabel"]=y.fields.name.label),D.search(y.iterator),j(),D.showActivity=function(){x({scope:D})},D.addJobTemplate=function(){c.path(c.path()+"/add")},D.editJobTemplate=function(a){c.path(c.path()+"/"+a)},D.deleteJobTemplate=function(a,b){var c=function(){$("#prompt-modal").on("hidden.bs.modal",function(){w("start")}),$("#prompt-modal").modal("hide");var b=z+a+"/";f.setUrl(b),f.destroy().success(function(){D.search(y.iterator)}).error(function(a){w("stop"),p(D,a,status,null,{hdr:"Error!",msg:"Call to "+b+" failed. DELETE returned status: "+status})})};k({hdr:"Delete",body:"Are you sure you want to delete "+b+"?",action:c})},D.submitJob=function(a){v({scope:D,id:a})}}function JobTemplatesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w){n("htmlTemplate");var x,y,z=o("job_templates"),A=g,B=h,C=B.inject(A,{mode:"add",related:!1}),D={},E={};C.parseType="yaml",u(C),C.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],C.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],C.playbook_options=[],C.allow_callbacks="false",B.reset(),l(),t({scope:C,master:D,check_field:"allow_callbacks",default_val:!1}),s({scope:C,form:A,current_item:null,list:p,field:"inventory"}),jQuery.extend(!0,E,q),E.name="cloudcredentials",E.iterator="cloudcredential",s({url:o("credentials")+"?cloud=true",scope:C,form:A,current_item:null,list:E,field:"cloud_credential",hdr:"Select Cloud Credential"}),s({url:o("credentials")+"?kind=ssh",scope:C,form:A,current_item:null,list:q,field:"credential",hdr:"Select Machine Credential"}),x=function(a,b){var c;a!==b&&C.project&&(v("start"),c=o("projects")+C.project+"/playbooks/",i.setUrl(c),i.get().success(function(a){var b,c=[];for(b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}b&&j("Waning",b,"alert-info")}).error(function(a,b){k(C,a,b,A,{hdr:"Error!",msg:"Failed to get project "+C.project+". GET returned status: "+b})}))},C.selectPlaybookUnregister&&C.selectPlaybookUnregister(),C.selectPlaybookUnregister=C.$watch("project_name",function(a,b){x(a,b),y(a,b)}),s({scope:C,form:A,current_item:null,list:r,field:"project"}),C.formSave=function(){B.clearApiErrors(),v("start");var a,b,c={};try{if(a="json"===C.parseType?JSON.parse(C.variables):jsyaml.load(C.variables),"object"!=typeof a)throw"failed to return an object!";for(b in A.fields)"select"===A.fields[b].type&&"playbook"!==b?c[b]=C[b].value:"variables"!==b&&(c[b]=C[b]);c.extra_vars=JSON.stringify(a,void 0," "),w(c.extra_vars)&&(c.extra_vars=""),i.setUrl(z),i.post(c).success(function(){v("stop");var a=d.path().replace(/^\//,"").split("/")[0];"job_templates"===a&&m(),m(1)}).error(function(a,b){v("stop"),k(C,a,b,A,{hdr:"Error!",msg:"Failed to add new job template. POST returned status: "+b})})}catch(e){v("stop"),j("Error","Error parsing extra variables. Parser returned: "+e)}},C.formReset=function(){B.reset();for(var a in D)C[a]=D[a]}}function JobTemplatesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D){p("htmlTemplate");var E,F,G=v("job_templates"),H=h,I=g,J=H.inject(I,{mode:"edit",related:!0}),K=0,L=d.path().replace(/^\//,"").split("/")[0],M={},N=f.id,O={};J.parseType="yaml",x(J),J.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],J.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],J.playbook_options=null,J.playbook=null,H.reset(),F=function(a){var b;C(a)||(b=v("projects")+a+"/playbooks/",A("start"),i.setUrl(b),i.get().success(function(a){var b;for(J.playbook_options=[],b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}A("stop"),b&&j("Waning",b,"alert-info")}).error(function(a,b){k(J,a,b,I,{hdr:"Error!",msg:"Failed to get project "+J.project+". GET returned status: "+b})}))},J.watchProjectUnregister&&J.watchProjectUnregister(),J.watchProjectUnregister=J.$watch("project_name",function(a,b){a!==b&&""!==b&&null!==b&&void 0!==b&&(J.playbook=null,F(J.project),E())}),J.removeJobTemplateLoadFinished&&J.removeJobTemplateLoadFinished(),J.removeJobTemplateLoadFinished=J.$on("jobTemplateLoadFinished",function(){if(K++,K>=2)for(var a in O)J.search(O[a].iterator)}),J.removeRelatedJobs&&J.removeRelatedJobs(),J.removeRelatedJobs=J.$on("relatedjobs",function(){var a,b;
+if(J.jobs&&J.jobs.length)for(a=0;a0)for(c=0;c/g," ");for(y in z.fields.status.searchOptions)if(z.fields.status.searchOptions[y].value===e.status){C[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[y];break}}C.search(z.iterator),j(),C.refresh=function(){x("start"),C.jobLoading=!1,u({scope:C,set:"jobs",iterator:"job",url:C.current_url})},C.refreshJob=C.refresh,C.editJob=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a)},C.viewEvents=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_events")},C.viewSummary=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_host_summaries")},C.deleteJob=function(a){f.setUrl(A+a+"/"),f.get().success(function(b){var c,d,e,g;"pending"===b.status||"running"===b.status||"waiting"===b.status?(d=b.related.cancel,e="cancel",g="Cancel Job"):(d=A+a+"/",e="delete",g="Delete Job"),c=function(){f.setUrl(d),"cancel"===e?f.post().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. POST returned status: "+b})}):f.destroy().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. DELETE returned status: "+b})})},k({hdr:g,body:"Are you sure you want to "+e+" job "+a+"?",action:c})}).error(function(a,b){p(C,a,b,null,{hdr:"Error!",msg:"Failed to get job details. GET returned status: "+b})})},C.submitJob=function(a,b){s({scope:C,id:a,template:b})}}function JobsEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){function A(a){if(null!==a&&""!==a&&void 0!==a){var b=v("projects")+a+"/playbooks/";i.setUrl(b),i.get().success(function(a){F.playbook_options=[];for(var b=0;b15?15:c}p("htmlTemplate");var C=v("jobs"),D=h,E=g,F=D.inject(E,{mode:"edit",related:!0}),G={},H=f.id,I={},J=0;D.reset(),F.job_id=H,F.parseType="yaml",F.statusSearchSpin=!1,F.jobLoadedRemove&&F.jobLoadedRemove(),F.jobLoadedRemove=F.$on("jobLoaded",function(a,b){A(F.project),F[E.name+"ReadOnly"]="new"===F.status?!1:!0,$("#forks-slider").slider("option","value",F.forks),$("#forks-slider").slider("disable"),$('input[type="checkbox"]').attr("disabled","disabled"),$('input[type="radio"]').attr("disabled","disabled"),$("#host_config_key-gen-btn").attr("disabled","disabled"),$("textarea").attr("readonly","readonly"),i.setUrl(F.template_url),i.get().success(function(a){var b=a.host_config_key?"true":"false";F.host_config_key=a.host_config_key,w({scope:F,master:G,check_field:"allow_callbacks",default_val:b}),F.callback_url=a.related?a.related.callback:"<< Job template not found >>",F.$emit("jobTemplateLoadFinished")}).error(function(){z("stop"),F.callback_url="<< Job template not found >>"}),b?(i.setUrl(b),i.get().success(function(a){F.cloud_credential_name=a.name,F.$emit("jobTemplateLoadFinished")}).error(function(a,b){k(F,a,b,null,{hdr:"Error!",msg:"Failed to related cloud credential. GET returned status: "+b})})):F.$emit("jobTemplateLoadFinished")}),F.removeJobTemplateLoadFinished&&F.removeJobTemplateLoadFinished(),F.removeJobTemplateLoadFinished=F.$on("jobTemplateLoadFinished",function(){J++,J>=3&&z("stop")}),F.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],F.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],F.playbook_options=null,F.playbook=null,z("start"),i.setUrl(C+":id/"),i.get({params:{id:H}}).success(function(a){var b,c,d,e,f,g;l();for(d in E.fields){if("variables"!==d&&null!==a[d]&&void 0!==a[d]){if("select"===E.fields[d].type)if(F[d+"_options"]&&F[d+"_options"].length>0)for(b=0;b/g," ");for(a in A.fields.scm_type.searchOptions)if(A.fields.scm_type.searchOptions[a].value===e.scm_type){F[A.iterator+"SearchSelectValue"]=A.fields.scm_type.searchOptions[a];break}}else if(e.status){F[A.iterator+"SearchValue"]=e.status,F[A.iterator+"SearchField"]="status",F[A.iterator+"SelectShow"]=!0,F[A.iterator+"SearchFieldLabel"]=A.fields.status.label,F[A.iterator+"SearchSelectOpts"]=A.fields.status.searchOptions;for(a in A.fields.status.searchOptions)if(A.fields.status.searchOptions[a].value===e.status){F[A.iterator+"SearchSelectValue"]=A.fields.status.searchOptions[a];break}}F.search(A.iterator)}),F.removeChoicesReady&&F.removeChoicesReady(),F.removeChoicesReady=F.$on("choicesReadyProject",function(){H++,2===H&&F.$emit("choicesCompleteProject")}),y({scope:F,url:B,field:"status",variable:"project_status_options",callback:"choicesReadyProject"}),y({scope:F,url:B,field:"scm_type",variable:"project_scm_type_options",callback:"choicesReadyProject"}),j(),F.showActivity=function(){x({scope:F})},F.addProject=function(){c.path(c.path()+"/add")},F.editProject=function(a){c.path(c.path()+"/"+a)},F.showSCMStatus=function(a){var b,c=F.$on("PostRefresh",function(){var d;for(b=0;bRefresh button to view the latest status.","alert-info")}).error(function(a,b){p(F,a,b,null,{hdr:"Error!",msg:"Call to "+c+" failed. GET status: "+b})})}),F.cancelUpdate=function(a,b){var c,d,e=!1;for(c=0;cRefresh button to view the latet status.","alert-info")},F.refresh=function(){w("start"),F.projectLoading=!1,v({scope:F,set:"projects",iterator:"project",url:F.current_url})},F.SCMUpdate=function(a){var b;for(b=0;bb;b++){for(d[b].match(/[A-Z]/g)?(""!==R&&R+1==b&&(y++,C++),R=b,o++):d[b].match(/[a-z]/g)?(""!==S&&S+1==b&&(z++,C++),S=b,p++):d[b].match(/[0-9]/g)?(b>0&&e-1>b&&s++,""!==T&&T+1==b&&(A++,C++),T=b,q++):d[b].match(/[^a-zA-Z0-9_]/g)&&(b>0&&e-1>b&&s++,""!==U&&U+1==b&&(B++,C++),U=b,r++),f=!1,g=0;e>g;g++)d[b]==d[g]&&b!=g&&(f=!0,x+=Math.abs(e/(g-b)));f&&(w++,v=e-w,x=Math.ceil(v?x/v:x))}for(h=0;23>h;h++)i=ib.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(D++,G++);for(h=0;8>h;h++)i=jb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(E++,G++);for(h=0;8>h;h++)i=kb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(F++,G++);o>0&&n>o&&(nScore=parseInt(nScore+2*(n-o)),V="+ "+parseInt(2*(n-o))),p>0&&n>p&&(nScore=parseInt(nScore+2*(n-p)),W="+ "+parseInt(2*(n-p))),q>0&&n>q&&(nScore=parseInt(nScore+q*P),X="+ "+parseInt(q*P)),r>0&&(nScore=parseInt(nScore+r*Q),Y="+ "+parseInt(r*Q)),s>0&&(nScore=parseInt(nScore+s*H),Z="+ "+parseInt(s*H)),(p>0||o>0)&&0===r&&0===q&&(nScore=parseInt(nScore-n),t=n,_="- "+n),0===p&&0===o&&0===r&&q>0&&(nScore=parseInt(nScore-n),u=n,ab="- "+n),w>0&&(nScore=parseInt(nScore-x),bb="- "+x),y>0&&(nScore=parseInt(nScore-y*I),cb="- "+parseInt(y*I)),z>0&&(nScore=parseInt(nScore-z*J),db="- "+parseInt(z*J)),A>0&&(nScore=parseInt(nScore-A*K),eb="- "+parseInt(A*K)),D>0&&(nScore=parseInt(nScore-D*L),fb="- "+parseInt(D*L)),E>0&&(nScore=parseInt(nScore-E*M),gb="- "+parseInt(E*M)),F>0&&(nScore=parseInt(nScore-F*N),hb="- "+parseInt(F*N)),nScore>100?nScore=100:0>nScore&&(nScore=0),k=$("#progbar"),l=$AnsibleConfig.password_strength,m=$AnsibleConfig.password_strength-15<0?0:$AnsibleConfig.password_strength-15,k.css("width",nScore+"%"),nScore>=0&&m>=nScore?(lb="Weak",k.addClass("progress-bar-danger"),k.removeClass("progress-bar-success progress-bar-warning")):nScore>m&&l>=nScore?(lb="Good",k.addClass("progress-bar-warning"),k.removeClass("progress-bar-success progress-bar-danger")):nScore>l&&(lb="Strong",k.addClass("progress-bar-success"),k.removeClass("progress-bar-warning progress-bar-danger"))}else k=$("#progbar"),k.css("width","0%"),k.removeClass("progress-bar-success progress-bar-warning");return nScore}function AdminsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){var q=h,r=o("organizations")+e.organization_id+"/users/",s=i,t="select",u=s.inject(h,{mode:t}),v=o("organizations")+e.organization_id+"/admins/";p({scope:u,list:q,url:v,returnToCaller:1}),l({scope:u,set:"admins",list:q,url:r}),m({scope:u,list:q,url:r}),u.search(q.iterator),j()}function Authenticate(a,b,c,d,e,f,g,h,i,j,k){var l,m,n,o;l=function(){$("#login-username").focus()},n=k(d.sessionExpired)?a.get("sessionExpired"):d.sessionExpired,m=function(){return k(d.lastPath)?a.get("lastPath"):d.lastPath},$AnsibleConfig.debug_mode&&console&&(console.log("User session expired: "+n),console.log("Last URL: "+m())),$(".modal[aria-hidden=false]").each(function(){"login-modal"!==$(this).attr("id")&&$(this).modal("hide")}),i("stop"),$("#login-modal").modal({show:!0,keyboard:!1,backdrop:"static"}),$("#login-modal").on("shown.bs.modal",function(){l()}),o=angular.element(document.getElementById("login-modal")).scope(),o.login_username=null,o.login_password=null,o.loginForm.login_username.$setPristine(),o.loginForm.login_password.$setPristine(),"/logout"===e.path()&&f.logout(),d.userLoggedIn=!1,a.put("userLoggedIn",!1),$("#login-password").bind("keypress",function(a){var b=a.keyCode?a.keyCode:a.which;13===b&&$("#login-button").click()}),o.reset=function(){$("#login-form input").each(function(){$(this).val("")})},o.systemLogin=function(a,b){$(".api-error").empty();var c;k(a)||k(b)?h("Error!","Please provide a username and password before attempting to login.","alert-danger",l):(i("start"),f.retrieveToken(a,b).success(function(a,b){$("#login-modal").modal("hide"),c=a.token,f.setToken(a.token,a.expires),d.sessionTimer=j.init(),f.getUser().success(function(a){f.setUserInfo(a),d.user_is_superuser=a.results[0].is_superuser,f.getLicense().success(function(a){f.setLicense(a.license_info),m()?e.path(m()):e.url("/home?login=true")}).error(function(){i("stop"),h("Error","Failed to access user information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){i("stop"),h("Error","Failed to access license information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){var c,d,e;if(i("stop"),a.non_field_errors&&0===a.non_field_errors.length)for(e in a)o[e+"Error"]=a[e][0];else a.non_field_errors&&a.non_field_errors.length>0?(c="Error",d=a.non_field_errors[0]):(c="Error",d="The login attempt failed with a status of: "+b),o.reset(),h(c,d,"alert-danger",l)}))}}function CredentialsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){o("htmlTemplate"),t("start");var v,w=h,x=q("credentials"),y=i,z=c.path().replace(/^\//,"").split("/")[0],A="credentials"===z?"edit":"select",B=y.inject(w,{mode:A});B.selected=[],B.credentialLoading=!0,v=q(z)+("users"===z?e.user_id+"/credentials/":e.team_id+"/credentials/"),r({scope:B,list:w,url:v,returnToCaller:1}),B.removePostRefresh&&B.removePostRefresh(),B.removePostRefresh=B.$on("PostRefresh",function(){var a,b;for(t("stop"),$("#prompt-modal").off(),w.fields.kind.searchOptions=B.credential_kind_options,a=0;a/g," ");for(x in z.fields.status.searchOptions)if(z.fields.status.searchOptions[x].value===b.status){B[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[x];break}}if(b.source){B[z.iterator+"SearchField"]="source",B[z.iterator+"SelectShow"]=!0,B[z.iterator+"SearchSelectOpts"]=z.fields.source.searchOptions,B[z.iterator+"SearchFieldLabel"]=z.fields.source.label.replace(/ /g," ");for(x in z.fields.source.searchOptions)if(z.fields.source.searchOptions[x].value===b.source){B[z.iterator+"SearchSelectValue"]=z.fields.source.searchOptions[x];break}b.status&&(B[z.iterator+"ExtraParms"]="&inventory_source__status__icontains="+b.status)}b.has_external_source&&(B[z.iterator+"SearchField"]="has_external_source",B[z.iterator+"SearchValue"]=z.fields.has_external_source.searchValue,B[z.iterator+"InputDisable"]=!0,B[z.iterator+"SearchType"]="in",B[z.iterator+"SearchFieldLabel"]=z.fields.has_external_source.label),B.search(z.iterator),f(),B.showActivity=function(){p({scope:B})},B.editGroup=function(a,b){q({scope:B,group_id:a,inventory_id:b,groups_reload:!1})},B.viewUpdateStatus=function(a){B.groups=B.home_groups,o({scope:B,tree_id:a})},B.updateGroup=function(a){var b=w({list:B.home_groups,key:"id",val:a});b&&(u(b.source)||("updating"===b.status?s("Update in Progress","The inventory update process is currently running for group "+b.name+". Use the Refresh button to monitor the status.","alert-info"):(r("start"),t.setUrl(b.related.inventory_source),t.get().success(function(a){v({scope:B,url:a.related.update,group_name:a.summary_fields.group.name,group_source:a.source,tree_id:b.id,group_id:b.id})}).error(function(a,c){e(B,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+b.related.inventory_source+" POST returned status: "+c})}))))},B.refresh=function(){B.search(z.iterator,null,!1,!0)}}function HomeHosts(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){h("htmlTemplate");var s=d,t=c,u=i("hosts"),v=s.inject(t,{mode:"edit"});v.removePostRefresh&&v.removePostRefresh(),v.removePostRefresh=v.$on("PostRefresh",function(){for(var a=0;a0?(z.inventories[a].failed_hosts_tip=z.inventories[a].hosts_with_active_failures+(1===z.inventories[a].hosts_with_active_failures?" host":" hosts")+" with job failures. Click to view details.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="true"):0===z.inventories[a].total_hosts?(z.inventories[a].failed_hosts_tip="No hosts defined. Click to add.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="na"):(z.inventories[a].failed_hosts_tip=z.inventories[a].total_hosts+(z.inventories[a].total_hosts>1?" hosts":" host")+" with no job failures. Click to view details.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="false"),z.inventories[a].status=z.inventories[a].inventory_sources_with_failures+" / "+z.inventories[a].total_inventory_sources,z.inventories[a].inventory_sources_with_failures>0?(z.inventories[a].status_tip=z.inventories[a].inventory_sources_with_failures+" cloud "+(1===z.inventories[a].inventory_sources_with_failures?"source":"sources")+" with failures. Click to view details.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="failed"):0===z.inventories[a].total_inventory_sources?(z.inventories[a].status_tip="Not synced with a cloud source. Click to edit.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="na"):(z.inventories[a].status_tip=z.inventories[a].total_inventory_sources+" cloud "+(z.inventories[a].total_inventory_sources>1?"sources":"source")+" with no failures. Click to view details.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="successful")
+}),z.removeRefreshInventories&&z.removeRefreshInventories(),z.removeRefreshInventories=z.$on("RefreshInventories",function(){z.search(u.iterator)}),z.showActivity=function(){s({scope:z})},z.editInventoryProperties=function(a){t({scope:z,inventory_id:a})},z.addInventory=function(){c.path(c.path()+"/add")},z.editInventory=function(a){c.path(c.path()+"/"+a)},z.deleteInventory=function(a,b){var c=function(){var b=v+a+"/";$("#prompt-modal").on("hidden.bs.modal",function(){r("start")}),$("#prompt-modal").modal("hide"),f.setUrl(b),f.destroy().success(function(){z.search(u.iterator)}).error(function(a,c){r("stop"),p(z,a,c,null,{hdr:"Error!",msg:"Call to "+b+" failed. DELETE returned status: "+c})})};k({hdr:"Delete",body:"Are you sure you want to delete "+b+"?",action:c})},z.lookupOrganization=function(a){f.setUrl(q("organizations")+a+"/"),f.get().success(function(a){return a.name})},z.viewJobs=function(a){c.url("/jobs/?inventory__int="+a)},z.viewFailedJobs=function(a){c.url("/jobs/?inventory__int="+a+"&status=failed")}}function InventoriesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v){n("htmlTemplate");var w,x=t("inventory"),y=g,z=h;y.well=!0,y.formLabelSize=null,y.formFieldSize=null,w=z.inject(y,{mode:"add",related:!1}),w.inventoryParseType="yaml",z.reset(),l(),u(w,"inventory_variables","inventoryParseType"),s({scope:w,form:y,current_item:f.organization_id?f.organization_id:null,list:p,field:"organization"}),w.formSave=function(){z.clearApiErrors(),v("start");try{var a,b,c;if(b="json"===w.inventoryParseType?JSON.parse(w.inventory_variables):jsyaml.load(w.inventory_variables),"object"!=typeof b)throw"failed to return an object!";c={};for(a in y.fields)"inventory_variables"!==a&&(y.fields[a].realName?c[y.fields[a].realName]=w[a]:c[a]=w[a]);i.setUrl(x),i.post(c).success(function(a){var c=a.id;w.inventory_variables?(i.setUrl(a.related.variable_data),i.put(b).success(function(){v("stop"),d.path("/inventories/"+c+"/")}).error(function(a,b){v("stop"),k(w,a,b,null,{hdr:"Error!",msg:"Failed to add inventory varaibles. PUT returned status: "+b})})):(v("stop"),d.path("/inventories/"+c+"/"))}).error(function(a,b){v("stop"),k(w,a,b,y,{hdr:"Error!",msg:"Failed to add new inventory. Post returned status: "+b})})}catch(e){v("stop"),j("Error","Error parsing inventory variables. Parser returned: "+e)}},w.formReset=function(){z.reset()}}function InventoriesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P){f("htmlTemplate");var Q=e,R=g;a.inventory_id=c.inventory_id,r({path:b.path(),title:"{{ inventory_name }}"}),a.removeGroupTreeLoaded&&a.removeGroupTreeLoaded(),a.removeGroupTreeLoaded=a.$on("GroupTreeLoaded",function(b,c,e){var f,g;f=angular.element(document.getElementById("breadcrumbs")),f.html(q({list:R,mode:"edit"})),d(f)(a),Q.inject(R,{mode:"edit",id:"groups-container",breadCrumbs:!1,searchSize:"col-lg-5 col-md-5 col-sm-5"}),a.groups=e,a.inventory_name=c,a.groups.length>0?(a.selected_tree_id=a.groups[0].id,a.selected_group_id=a.groups[0].group_id,a.groups[0].selected_class="selected",a.groups[0].active_class="active-row",a.selected_group_name=a.groups[0].name):(a.selected_tree_id=null,a.selected_group_id=null),a.show_failures=!1,l({scope:a,inventory_id:a.inventory_id,tree_id:a.selected_tree_id,group_id:a.selected_group_id}),setTimeout(function(){$("#groups_table .name-column").each(function(){var a,b,c,d,e;a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%",$(this).find(".group-name").css({width:e})}),L("#groups_table .group-name a"),L("#hosts_table .host-name a")},2500),M(),g=P("inventoryAutoHelp"),"off"!==g&&a.autoShowGroupHelp&&a.showGroupHelp({autoShow:!0})}),a.removeGroupTreeRefreshed&&a.removeGroupTreeRefreshed(),a.removeGroupTreeRefreshed=a.$on("GroupTreeRefreshed",function(){setTimeout(function(){L("#groups_table .group-name a")},2500),a.showHosts(a.selected_tree_id,a.selected_group_id,!1)}),a.removeGroupDeleteCompleted&&a.removeGroupDeleteCompleted(),a.removeGroupDeleteCompleted=a.$on("GroupDeleteCompleted",function(){a.selected_tree_id=1,a.selected_group_id=null,i({scope:a,inventory_id:a.inventory_id,refresh:!0})}),a.removeCopMoveGroup&&a.removeCopyMoveGroup(),a.removeCopyMoveGroup=a.$on("CopyMoveGroup",function(b,c,d){G({scope:a,target_tree_id:d,inbound_tree_id:c})}),a.removeCopMoveHost&&a.removeCopyMoveHost(),a.removeCopyMoveHost=a.$on("CopyMoveHost",function(b,c,d){H({scope:a,target_tree_id:c,host_id:d})}),a.showHosts=function(b,c,d){if(null!==b){j("start"),a.selected_tree_id=b,a.selected_group_id=c,a.hosts=[],a.show_failures=d;for(var e=0;e"+c.name+". Use the Refresh button to monitor the status.","alert-info"):(j("start"),t.setUrl(c.related.inventory_source),t.get().success(function(b){v({scope:a,url:b.related.update,group_name:b.summary_fields.group.name,group_source:b.source,tree_id:c.id,group_id:c.group_id})}).error(function(b,d){j("stop"),u(a,b,d,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+c.related.inventory_source+" POST returned status: "+d})}))))},a.cancelUpdate=function(b){z({scope:a,tree_id:b})},a.toggle=function(b){x({scope:a,list:R,id:b})},a.refreshGroups=function(b,c){b&&(a.selected_tree_id=b,a.selected_group_id=c),i({scope:a,inventory_id:a.inventory_id,refresh:!0})},a.viewUpdateStatus=function(b,c){y({scope:a,tree_id:b,group_id:c})},a.deleteGroup=function(b,c){p({scope:a,tree_id:b,group_id:c,inventory_id:a.inventory_id})},a.createHost=function(){B({scope:a})},a.editInventoryProperties=function(){C({scope:a,inventory_id:a.inventory_id})},a.editHost=function(b){D({scope:a,host_id:b,inventory_id:a.inventory_id})},a.deleteHost=function(b,c){E({scope:a,host_id:b,host_name:c})},a.toggleHostEnabled=function(b,c){F({scope:a,host_id:b,external_source:c})},a.showGroupActivity=function(){var b,c,d;a.selected_group_id?(d=A({list:a.groups,key:"id",val:a.selected_tree_id}),b=J("activity_stream")+"?group__id="+a.selected_group_id,c="Showing all activities for group "+d.name):(c="Showing all activities for all "+a.inventory_name+" groups",b=J("activity_stream")+"?group__inventory__id="+a.inventory_id),I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showHostActivity=function(){var b,c;c="Showing all activities for all "+a.inventory_name+" hosts",b=J("activity_stream")+"?host__inventory__id="+a.inventory_id,I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showJobSummary=function(a){K({job_id:a})},a.showGroupHelp=function(a){var b={defn:O};a&&(b.autoShow=a.autoShow||!1),N(b)},i({scope:a,inventory_id:a.inventory_id,refresh:!1})}function JobEventsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){function y(a){var b,c,d,e,f,g="",h=!1;if(a.res){if("string"==typeof a.res)c=a.res.match(/\n/g),d=c?c.length:1,d=d>10?10:d,h=!0,g+='
\n',g+="\n",g+='\n",g+="
\n";else for(e in a.res){if(("msg"===e||"stdout"===e||"stderr"===e)&&null!==a.res[e]&&""!==a.res[e]){switch(g+='
\n",h=!0)}g=h?'\n":""}return g=a.hosts?''+a.host+"\n"+g:""===g?null:g}p("htmlTemplate");var z,A=i,B=r("jobs")+f.id+"/job_events/",C=j,D=C.inject(A,{mode:"edit"});A.base=d.path(),D.job_id=f.id,c.flashMessage=null,D.selected=[],D.expand=!0,D.parentNode="parent-event",D.childNode="child-event",D.removeSetHostLinks&&D.removeSetHostLinks(),D.removeSetHostLinks=D.$on("SetHostLinks",function(a,b){for(var c=0;c15?5:e,$('textarea[name="'+c+'"]').attr("rows",e)));break;case"module_name":case"module_args":a.event_data.res&&a.event_data.res.invocation&&(t[c]=a.event_data.res.invocation.fld)}q("stop")}).error(function(a){k(t,a,status,null,{hdr:"Error!",msg:"Failed to retrieve host: "+f.event_id+". GET status: "+status})}),t.navigateBack=function(){var a="/jobs/"+f.job_id+"/job_events";f.page&&(a+="?page="+f.page),d.url(a)},t.rawView=function(){p({event_id:t.id})}}function JobHostSummaryList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){o("htmlTemplate");var u=h,v=c.path().replace(/^\//,"").split("/")[0],w=q(v)+e.id+"/job_host_summaries/",x=i,y=x.inject(u,{mode:"edit"});u.index="hosts"===v?!1:!0,y.selected=[],"hosts"===v?(y.job_id=null,y.host_id=e.id):(y.job_id=e.id,y.host_id=null),y.RemoveSetHostLink&&y.RemoveSetHostLink(),y.RemoveSetHostLink=y.$on("setHostLink",function(a,b){for(var c=0;c0?y.jobhosts[0].summary_fields.host.name:"Host"}),e.inventory&&y.$emit("setHostLink",e.inventory))}),l({scope:y,set:"jobhosts",list:u,url:w}),m({scope:y,list:u,url:w}),e.host_name&&(y[u.iterator+"SearchField"]="host",y[u.iterator+"SearchValue"]=e.host_name,y[u.iterator+"SearchFieldLabel"]=u.fields.host.label),y.search(u.iterator),y.showEvents=function(a,b){f.setUrl(b),f.get().success(function(b){j({path:"/jobs/"+b.id,title:b.name}),c.url("/jobs/"+b.id+"/job_events/?host="+encodeURI(a))}).error(function(a,c){p(y,a,c,null,{hdr:"Error!",msg:"Failed to lookup last job: "+b+". GET status: "+c})})},y.showJob=function(a){c.path("/jobs/"+a)},y.refresh=function(){null===y.host_id&&(y.jobSearchSpin=!0,y.jobLoading=!0,t("start"),r({scope:y,set:"jobhosts",iterator:"jobhost",url:y.current_url}))}}function JobTemplatesList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){o("htmlTemplate");var y=h,z=q("job_templates"),A=i,B=c.path().replace(/^\//,"").split("/")[0],C="job_templates"===B?"edit":"select",D=A.inject(y,{mode:C});b.flashMessage=null,D.removePostRefresh&&D.removePostRefresh(),D.removePostRefresh=D.$on("PostRefresh",function(){w("stop"),$("#prompt-modal").off()}),l({scope:D,set:"job_templates",list:y,url:z}),m({scope:D,list:y,url:z}),e.name&&(D[y.iterator+"SearchField"]="name",D[y.iterator+"SearchValue"]=e.name,D[y.iterator+"SearchFieldLabel"]=y.fields.name.label),D.search(y.iterator),j(),D.showActivity=function(){x({scope:D})},D.addJobTemplate=function(){c.path(c.path()+"/add")},D.editJobTemplate=function(a){c.path(c.path()+"/"+a)},D.deleteJobTemplate=function(a,b){var c=function(){$("#prompt-modal").on("hidden.bs.modal",function(){w("start")}),$("#prompt-modal").modal("hide");var b=z+a+"/";f.setUrl(b),f.destroy().success(function(){D.search(y.iterator)}).error(function(a){w("stop"),p(D,a,status,null,{hdr:"Error!",msg:"Call to "+b+" failed. DELETE returned status: "+status})})};k({hdr:"Delete",body:"Are you sure you want to delete "+b+"?",action:c})},D.submitJob=function(a){v({scope:D,id:a})}}function JobTemplatesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w){n("htmlTemplate");var x,y,z=o("job_templates"),A=g,B=h,C=B.inject(A,{mode:"add",related:!1}),D={},E={};C.parseType="yaml",u(C),C.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],C.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],C.playbook_options=[],C.allow_callbacks="false",B.reset(),l(),t({scope:C,master:D,check_field:"allow_callbacks",default_val:!1}),s({scope:C,form:A,current_item:null,list:p,field:"inventory"}),jQuery.extend(!0,E,q),E.name="cloudcredentials",E.iterator="cloudcredential",s({url:o("credentials")+"?cloud=true",scope:C,form:A,current_item:null,list:E,field:"cloud_credential",hdr:"Select Cloud Credential"}),s({url:o("credentials")+"?kind=ssh",scope:C,form:A,current_item:null,list:q,field:"credential",hdr:"Select Machine Credential"}),x=function(a,b){var c;a!==b&&C.project&&(v("start"),c=o("projects")+C.project+"/playbooks/",i.setUrl(c),i.get().success(function(a){var b,c=[];for(b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}b&&j("Waning",b,"alert-info")}).error(function(a,b){k(C,a,b,A,{hdr:"Error!",msg:"Failed to get project "+C.project+". GET returned status: "+b})}))},C.selectPlaybookUnregister&&C.selectPlaybookUnregister(),C.selectPlaybookUnregister=C.$watch("project_name",function(a,b){x(a,b),y(a,b)}),s({scope:C,form:A,current_item:null,list:r,field:"project"}),C.formSave=function(){B.clearApiErrors(),v("start");var a,b,c={};try{if(a="json"===C.parseType?JSON.parse(C.variables):jsyaml.load(C.variables),"object"!=typeof a)throw"failed to return an object!";for(b in A.fields)"select"===A.fields[b].type&&"playbook"!==b?c[b]=C[b].value:"variables"!==b&&(c[b]=C[b]);c.extra_vars=JSON.stringify(a,void 0," "),w(c.extra_vars)&&(c.extra_vars=""),i.setUrl(z),i.post(c).success(function(){v("stop");var a=d.path().replace(/^\//,"").split("/")[0];"job_templates"===a&&m(),m(1)}).error(function(a,b){v("stop"),k(C,a,b,A,{hdr:"Error!",msg:"Failed to add new job template. POST returned status: "+b})})}catch(e){v("stop"),j("Error","Error parsing extra variables. Parser returned: "+e)}},C.formReset=function(){B.reset();for(var a in D)C[a]=D[a]}}function JobTemplatesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D){p("htmlTemplate");var E,F,G=v("job_templates"),H=h,I=g,J=H.inject(I,{mode:"edit",related:!0}),K=0,L=d.path().replace(/^\//,"").split("/")[0],M={},N=f.id,O={};J.parseType="yaml",x(J),J.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],J.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],J.playbook_options=null,J.playbook=null,H.reset(),F=function(a){var b;C(a)||(b=v("projects")+a+"/playbooks/",A("start"),i.setUrl(b),i.get().success(function(a){var b;for(J.playbook_options=[],b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}A("stop"),b&&j("Waning",b,"alert-info")}).error(function(a,b){k(J,a,b,I,{hdr:"Error!",msg:"Failed to get project "+J.project+". GET returned status: "+b})}))},J.watchProjectUnregister&&J.watchProjectUnregister(),J.watchProjectUnregister=J.$watch("project_name",function(a,b){a!==b&&""!==b&&null!==b&&void 0!==b&&(J.playbook=null,F(J.project),E())}),J.removeJobTemplateLoadFinished&&J.removeJobTemplateLoadFinished(),J.removeJobTemplateLoadFinished=J.$on("jobTemplateLoadFinished",function(){if(K++,K>=2)for(var a in O)J.search(O[a].iterator)}),J.removeRelatedJobs&&J.removeRelatedJobs(),J.removeRelatedJobs=J.$on("relatedjobs",function(){var a,b;if(J.jobs&&J.jobs.length)for(a=0;a0)for(c=0;c/g," ");for(y in z.fields.status.searchOptions)if(z.fields.status.searchOptions[y].value===e.status){C[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[y];break}}C.search(z.iterator),j(),C.refresh=function(){x("start"),C.jobLoading=!1,u({scope:C,set:"jobs",iterator:"job",url:C.current_url})},C.refreshJob=C.refresh,C.editJob=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a)},C.viewEvents=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_events")},C.viewSummary=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_host_summaries")},C.deleteJob=function(a){f.setUrl(A+a+"/"),f.get().success(function(b){var c,d,e,g;"pending"===b.status||"running"===b.status||"waiting"===b.status?(d=b.related.cancel,e="cancel",g="Cancel Job"):(d=A+a+"/",e="delete",g="Delete Job"),c=function(){f.setUrl(d),"cancel"===e?f.post().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. POST returned status: "+b})}):f.destroy().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. DELETE returned status: "+b})})},k({hdr:g,body:"Are you sure you want to "+e+" job "+a+"?",action:c})}).error(function(a,b){p(C,a,b,null,{hdr:"Error!",msg:"Failed to get job details. GET returned status: "+b})})},C.submitJob=function(a,b){s({scope:C,id:a,template:b})}}function JobsEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){function A(a){if(null!==a&&""!==a&&void 0!==a){var b=v("projects")+a+"/playbooks/";i.setUrl(b),i.get().success(function(a){F.playbook_options=[];for(var b=0;b15?15:c}p("htmlTemplate");var C=v("jobs"),D=h,E=g,F=D.inject(E,{mode:"edit",related:!0}),G={},H=f.id,I={},J=0;D.reset(),F.job_id=H,F.parseType="yaml",F.statusSearchSpin=!1,F.jobLoadedRemove&&F.jobLoadedRemove(),F.jobLoadedRemove=F.$on("jobLoaded",function(a,b){A(F.project),F[E.name+"ReadOnly"]="new"===F.status?!1:!0,$("#forks-slider").slider("option","value",F.forks),$("#forks-slider").slider("disable"),$('input[type="checkbox"]').attr("disabled","disabled"),$('input[type="radio"]').attr("disabled","disabled"),$("#host_config_key-gen-btn").attr("disabled","disabled"),$("textarea").attr("readonly","readonly"),i.setUrl(F.template_url),i.get().success(function(a){var b=a.host_config_key?"true":"false";F.host_config_key=a.host_config_key,w({scope:F,master:G,check_field:"allow_callbacks",default_val:b}),F.callback_url=a.related?a.related.callback:"<< Job template not found >>",F.$emit("jobTemplateLoadFinished")}).error(function(){z("stop"),F.callback_url="<< Job template not found >>"}),b?(i.setUrl(b),i.get().success(function(a){F.cloud_credential_name=a.name,F.$emit("jobTemplateLoadFinished")}).error(function(a,b){k(F,a,b,null,{hdr:"Error!",msg:"Failed to related cloud credential. GET returned status: "+b})})):F.$emit("jobTemplateLoadFinished")}),F.removeJobTemplateLoadFinished&&F.removeJobTemplateLoadFinished(),F.removeJobTemplateLoadFinished=F.$on("jobTemplateLoadFinished",function(){J++,J>=3&&z("stop")}),F.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],F.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],F.playbook_options=null,F.playbook=null,z("start"),i.setUrl(C+":id/"),i.get({params:{id:H}}).success(function(a){var b,c,d,e,f,g;l();for(d in E.fields){if("variables"!==d&&null!==a[d]&&void 0!==a[d]){if("select"===E.fields[d].type)if(F[d+"_options"]&&F[d+"_options"].length>0)for(b=0;b/g," ");for(a in A.fields.scm_type.searchOptions)if(A.fields.scm_type.searchOptions[a].value===e.scm_type){F[A.iterator+"SearchSelectValue"]=A.fields.scm_type.searchOptions[a];break}}else if(e.status){F[A.iterator+"SearchValue"]=e.status,F[A.iterator+"SearchField"]="status",F[A.iterator+"SelectShow"]=!0,F[A.iterator+"SearchFieldLabel"]=A.fields.status.label,F[A.iterator+"SearchSelectOpts"]=A.fields.status.searchOptions;for(a in A.fields.status.searchOptions)if(A.fields.status.searchOptions[a].value===e.status){F[A.iterator+"SearchSelectValue"]=A.fields.status.searchOptions[a];break}}F.search(A.iterator)}),F.removeChoicesReady&&F.removeChoicesReady(),F.removeChoicesReady=F.$on("choicesReadyProject",function(){H++,2===H&&F.$emit("choicesCompleteProject")}),y({scope:F,url:B,field:"status",variable:"project_status_options",callback:"choicesReadyProject"}),y({scope:F,url:B,field:"scm_type",variable:"project_scm_type_options",callback:"choicesReadyProject"}),j(),F.showActivity=function(){x({scope:F})},F.addProject=function(){c.path(c.path()+"/add")},F.editProject=function(a){c.path(c.path()+"/"+a)},F.showSCMStatus=function(a){var b,c=F.$on("PostRefresh",function(){var d;for(b=0;bRefresh button to view the latest status.","alert-info")}).error(function(a,b){p(F,a,b,null,{hdr:"Error!",msg:"Call to "+c+" failed. GET status: "+b})})}),F.cancelUpdate=function(a,b){var c,d,e=!1;for(c=0;cRefresh button to view the latet status.","alert-info")},F.refresh=function(){w("start"),F.projectLoading=!1,v({scope:F,set:"projects",iterator:"project",url:F.current_url})},F.SCMUpdate=function(a){var b;for(b=0;bb;b++){for(d[b].match(/[A-Z]/g)?(""!==R&&R+1==b&&(y++,C++),R=b,o++):d[b].match(/[a-z]/g)?(""!==S&&S+1==b&&(z++,C++),S=b,p++):d[b].match(/[0-9]/g)?(b>0&&e-1>b&&s++,""!==T&&T+1==b&&(A++,C++),T=b,q++):d[b].match(/[^a-zA-Z0-9_]/g)&&(b>0&&e-1>b&&s++,""!==U&&U+1==b&&(B++,C++),U=b,r++),f=!1,g=0;e>g;g++)d[b]==d[g]&&b!=g&&(f=!0,x+=Math.abs(e/(g-b)));f&&(w++,v=e-w,x=Math.ceil(v?x/v:x))}for(h=0;23>h;h++)i=ib.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(D++,G++);for(h=0;8>h;h++)i=jb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(E++,G++);for(h=0;8>h;h++)i=kb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(F++,G++);o>0&&n>o&&(nScore=parseInt(nScore+2*(n-o)),V="+ "+parseInt(2*(n-o))),p>0&&n>p&&(nScore=parseInt(nScore+2*(n-p)),W="+ "+parseInt(2*(n-p))),q>0&&n>q&&(nScore=parseInt(nScore+q*P),X="+ "+parseInt(q*P)),r>0&&(nScore=parseInt(nScore+r*Q),Y="+ "+parseInt(r*Q)),s>0&&(nScore=parseInt(nScore+s*H),Z="+ "+parseInt(s*H)),(p>0||o>0)&&0===r&&0===q&&(nScore=parseInt(nScore-n),t=n,_="- "+n),0===p&&0===o&&0===r&&q>0&&(nScore=parseInt(nScore-n),u=n,ab="- "+n),w>0&&(nScore=parseInt(nScore-x),bb="- "+x),y>0&&(nScore=parseInt(nScore-y*I),cb="- "+parseInt(y*I)),z>0&&(nScore=parseInt(nScore-z*J),db="- "+parseInt(z*J)),A>0&&(nScore=parseInt(nScore-A*K),eb="- "+parseInt(A*K)),D>0&&(nScore=parseInt(nScore-D*L),fb="- "+parseInt(D*L)),E>0&&(nScore=parseInt(nScore-E*M),gb="- "+parseInt(E*M)),F>0&&(nScore=parseInt(nScore-F*N),hb="- "+parseInt(F*N)),nScore>100?nScore=100:0>nScore&&(nScore=0),k=$("#progbar"),l=$AnsibleConfig.password_strength,m=$AnsibleConfig.password_strength-15<0?0:$AnsibleConfig.password_strength-15,k.css("width",nScore+"%"),nScore>=0&&m>=nScore?(lb="Weak",k.addClass("progress-bar-danger"),k.removeClass("progress-bar-success progress-bar-warning")):nScore>m&&l>=nScore?(lb="Good",k.addClass("progress-bar-warning"),k.removeClass("progress-bar-success progress-bar-danger")):nScore>l&&(lb="Strong",k.addClass("progress-bar-success"),k.removeClass("progress-bar-warning progress-bar-danger"))}else k=$("#progbar"),k.css("width","0%"),k.removeClass("progress-bar-success progress-bar-warning");return nScore}function AdminsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){var q=h,r=o("organizations")+e.organization_id+"/users/",s=i,t="select",u=s.inject(h,{mode:t}),v=o("organizations")+e.organization_id+"/admins/";p({scope:u,list:q,url:v,returnToCaller:1}),l({scope:u,set:"admins",list:q,url:r}),m({scope:u,list:q,url:r}),u.search(q.iterator),j()}function Authenticate(a,b,c,d,e,f,g,h,i,j,k){var l,m,n,o;l=function(){$("#login-username").focus()},n=k(d.sessionExpired)?a.get("sessionExpired"):d.sessionExpired,m=function(){return k(d.lastPath)?a.get("lastPath"):d.lastPath},$AnsibleConfig.debug_mode&&console&&(console.log("User session expired: "+n),console.log("Last URL: "+m())),$(".modal[aria-hidden=false]").each(function(){"login-modal"!==$(this).attr("id")&&$(this).modal("hide")}),i("stop"),$("#login-modal").modal({show:!0,keyboard:!1,backdrop:"static"}),$("#login-modal").on("shown.bs.modal",function(){l()}),o=angular.element(document.getElementById("login-modal")).scope(),o.login_username=null,o.login_password=null,o.loginForm.login_username.$setPristine(),o.loginForm.login_password.$setPristine(),"/logout"===e.path()&&f.logout(),d.userLoggedIn=!1,a.put("userLoggedIn",!1),$("#login-password").bind("keypress",function(a){var b=a.keyCode?a.keyCode:a.which;13===b&&$("#login-button").click()}),o.reset=function(){$("#login-form input").each(function(){$(this).val("")})},o.systemLogin=function(a,b){$(".api-error").empty();var c;k(a)||k(b)?h("Error!","Please provide a username and password before attempting to login.","alert-danger",l):(i("start"),f.retrieveToken(a,b).success(function(a,b){$("#login-modal").modal("hide"),c=a.token,f.setToken(a.token,a.expires),d.sessionTimer=j.init(),f.getUser().success(function(a){f.setUserInfo(a),d.user_is_superuser=a.results[0].is_superuser,f.getLicense().success(function(a){f.setLicense(a.license_info),m()?e.path(m()):e.url("/home?login=true")}).error(function(){i("stop"),h("Error","Failed to access user information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){i("stop"),h("Error","Failed to access license information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){var c,d,e;if(i("stop"),a.non_field_errors&&0===a.non_field_errors.length)for(e in a)o[e+"Error"]=a[e][0];else a.non_field_errors&&a.non_field_errors.length>0?(c="Error",d=a.non_field_errors[0]):(c="Error",d="The login attempt failed with a status of: "+b),o.reset(),h(c,d,"alert-danger",l)}))}}function CredentialsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){o("htmlTemplate"),t("start");var v,w=h,x=q("credentials"),y=i,z=c.path().replace(/^\//,"").split("/")[0],A="credentials"===z?"edit":"select",B=y.inject(w,{mode:A});B.selected=[],B.credentialLoading=!0,v=q(z)+("users"===z?e.user_id+"/credentials/":e.team_id+"/credentials/"),r({scope:B,list:w,url:v,returnToCaller:1}),B.removePostRefresh&&B.removePostRefresh(),B.removePostRefresh=B.$on("PostRefresh",function(){var a,b;for(t("stop"),$("#prompt-modal").off(),w.fields.kind.searchOptions=B.credential_kind_options,a=0;a/g," ");for(x in z.fields.status.searchOptions)if(z.fields.status.searchOptions[x].value===b.status){B[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[x];break}}if(b.source){B[z.iterator+"SearchField"]="source",B[z.iterator+"SelectShow"]=!0,B[z.iterator+"SearchSelectOpts"]=z.fields.source.searchOptions,B[z.iterator+"SearchFieldLabel"]=z.fields.source.label.replace(/ /g," ");for(x in z.fields.source.searchOptions)if(z.fields.source.searchOptions[x].value===b.source){B[z.iterator+"SearchSelectValue"]=z.fields.source.searchOptions[x];break}b.status&&(B[z.iterator+"ExtraParms"]="&inventory_source__status__icontains="+b.status)}b.has_external_source&&(B[z.iterator+"SearchField"]="has_external_source",B[z.iterator+"SearchValue"]=z.fields.has_external_source.searchValue,B[z.iterator+"InputDisable"]=!0,B[z.iterator+"SearchType"]="in",B[z.iterator+"SearchFieldLabel"]=z.fields.has_external_source.label),B.search(z.iterator),f(),B.showActivity=function(){p({scope:B})},B.editGroup=function(a,b){q({scope:B,group_id:a,inventory_id:b,groups_reload:!1})},B.viewUpdateStatus=function(a){B.groups=B.home_groups,o({scope:B,tree_id:a})},B.updateGroup=function(a){var b=w({list:B.home_groups,key:"id",val:a});b&&(u(b.source)||("updating"===b.status?s("Update in Progress","The inventory update process is currently running for group "+b.name+". Use the Refresh button to monitor the status.","alert-info"):(r("start"),t.setUrl(b.related.inventory_source),t.get().success(function(a){v({scope:B,url:a.related.update,group_name:a.summary_fields.group.name,group_source:a.source,tree_id:b.id,group_id:b.id})}).error(function(a,c){e(B,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+b.related.inventory_source+" POST returned status: "+c})}))))},B.refresh=function(){B.search(z.iterator,null,!1,!0)}}function HomeHosts(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){h("htmlTemplate");var s=d,t=c,u=i("hosts"),v=s.inject(t,{mode:"edit"});v.removePostRefresh&&v.removePostRefresh(),v.removePostRefresh=v.$on("PostRefresh",function(){for(var a=0;a0?(z.inventories[a].failed_hosts_tip=z.inventories[a].hosts_with_active_failures+(1===z.inventories[a].hosts_with_active_failures?" host":" hosts")+" with job failures. Click to view details.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="true"):0===z.inventories[a].total_hosts?(z.inventories[a].failed_hosts_tip="No hosts defined. Click to add.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="na"):(z.inventories[a].failed_hosts_tip=z.inventories[a].total_hosts+(z.inventories[a].total_hosts>1?" hosts":" host")+" with no job failures. Click to view details.",z.inventories[a].failed_hosts_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].failed_hosts_class="false"),z.inventories[a].status=z.inventories[a].inventory_sources_with_failures+" / "+z.inventories[a].total_inventory_sources,z.inventories[a].inventory_sources_with_failures>0?(z.inventories[a].status_tip=z.inventories[a].inventory_sources_with_failures+" cloud "+(1===z.inventories[a].inventory_sources_with_failures?"source":"sources")+" with failures. Click to view details.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="failed"):0===z.inventories[a].total_inventory_sources?(z.inventories[a].status_tip="Not synced with a cloud source. Click to edit.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="na"):(z.inventories[a].status_tip=z.inventories[a].total_inventory_sources+" cloud "+(z.inventories[a].total_inventory_sources>1?"sources":"source")+" with no failures. Click to view details.",z.inventories[a].status_link="/#/inventories/"+z.inventories[a].id+"/",z.inventories[a].status_class="successful")}),z.removeRefreshInventories&&z.removeRefreshInventories(),z.removeRefreshInventories=z.$on("RefreshInventories",function(){z.search(u.iterator)}),z.showActivity=function(){s({scope:z})},z.editInventoryProperties=function(a){t({scope:z,inventory_id:a})},z.addInventory=function(){c.path(c.path()+"/add")},z.editInventory=function(a){c.path(c.path()+"/"+a)},z.deleteInventory=function(a,b){var c=function(){var b=v+a+"/";$("#prompt-modal").on("hidden.bs.modal",function(){r("start")}),$("#prompt-modal").modal("hide"),f.setUrl(b),f.destroy().success(function(){z.search(u.iterator)}).error(function(a,c){r("stop"),p(z,a,c,null,{hdr:"Error!",msg:"Call to "+b+" failed. DELETE returned status: "+c})})};k({hdr:"Delete",body:"Are you sure you want to delete "+b+"?",action:c})},z.lookupOrganization=function(a){f.setUrl(q("organizations")+a+"/"),f.get().success(function(a){return a.name})},z.viewJobs=function(a){c.url("/jobs/?inventory__int="+a)},z.viewFailedJobs=function(a){c.url("/jobs/?inventory__int="+a+"&status=failed")}}function InventoriesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v){n("htmlTemplate");var w,x=t("inventory"),y=g,z=h;y.well=!0,y.formLabelSize=null,y.formFieldSize=null,w=z.inject(y,{mode:"add",related:!1}),w.inventoryParseType="yaml",z.reset(),l(),u(w,"inventory_variables","inventoryParseType"),s({scope:w,form:y,current_item:f.organization_id?f.organization_id:null,list:p,field:"organization"}),w.formSave=function(){z.clearApiErrors(),v("start");try{var a,b,c;if(b="json"===w.inventoryParseType?JSON.parse(w.inventory_variables):jsyaml.load(w.inventory_variables),"object"!=typeof b)throw"failed to return an object!";c={};for(a in y.fields)"inventory_variables"!==a&&(y.fields[a].realName?c[y.fields[a].realName]=w[a]:c[a]=w[a]);i.setUrl(x),i.post(c).success(function(a){var c=a.id;w.inventory_variables?(i.setUrl(a.related.variable_data),i.put(b).success(function(){v("stop"),d.path("/inventories/"+c+"/")}).error(function(a,b){v("stop"),k(w,a,b,null,{hdr:"Error!",msg:"Failed to add inventory varaibles. PUT returned status: "+b})})):(v("stop"),d.path("/inventories/"+c+"/"))}).error(function(a,b){v("stop"),k(w,a,b,y,{hdr:"Error!",msg:"Failed to add new inventory. Post returned status: "+b})})}catch(e){v("stop"),j("Error","Error parsing inventory variables. Parser returned: "+e)}},w.formReset=function(){z.reset()}}function InventoriesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P){f("htmlTemplate");var Q=e,R=g;a.inventory_id=c.inventory_id,r({path:b.path(),title:"{{ inventory_name }}"}),a.removeGroupTreeLoaded&&a.removeGroupTreeLoaded(),a.removeGroupTreeLoaded=a.$on("GroupTreeLoaded",function(b,c,e){var f,g;f=angular.element(document.getElementById("breadcrumbs")),f.html(q({list:R,mode:"edit"})),d(f)(a),Q.inject(R,{mode:"edit",id:"groups-container",breadCrumbs:!1,searchSize:"col-lg-5 col-md-5 col-sm-5"}),a.groups=e,a.inventory_name=c,a.groups.length>0?(a.selected_tree_id=a.groups[0].id,a.selected_group_id=a.groups[0].group_id,a.groups[0].selected_class="selected",a.groups[0].active_class="active-row",a.selected_group_name=a.groups[0].name):(a.selected_tree_id=null,a.selected_group_id=null),a.show_failures=!1,l({scope:a,inventory_id:a.inventory_id,tree_id:a.selected_tree_id,group_id:a.selected_group_id}),setTimeout(function(){$("#groups_table .name-column").each(function(){var a,b,c,d,e;a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%",$(this).find(".group-name").css({width:e})}),L("#groups_table .group-name a"),L("#hosts_table .host-name a")},2500),M(),g=P("inventoryAutoHelp"),"off"!==g&&a.autoShowGroupHelp&&a.showGroupHelp({autoShow:!0})}),a.removeGroupTreeRefreshed&&a.removeGroupTreeRefreshed(),a.removeGroupTreeRefreshed=a.$on("GroupTreeRefreshed",function(){setTimeout(function(){L("#groups_table .group-name a")},2500),a.showHosts(a.selected_tree_id,a.selected_group_id,!1)}),a.removeGroupDeleteCompleted&&a.removeGroupDeleteCompleted(),a.removeGroupDeleteCompleted=a.$on("GroupDeleteCompleted",function(){a.selected_tree_id=1,a.selected_group_id=null,i({scope:a,inventory_id:a.inventory_id,refresh:!0})}),a.removeCopMoveGroup&&a.removeCopyMoveGroup(),a.removeCopyMoveGroup=a.$on("CopyMoveGroup",function(b,c,d){G({scope:a,target_tree_id:d,inbound_tree_id:c})}),a.removeCopMoveHost&&a.removeCopyMoveHost(),a.removeCopyMoveHost=a.$on("CopyMoveHost",function(b,c,d){H({scope:a,target_tree_id:c,host_id:d})}),a.showHosts=function(b,c,d){if(null!==b){j("start"),a.selected_tree_id=b,a.selected_group_id=c,a.hosts=[],a.show_failures=d;for(var e=0;e"+c.name+". Use the Refresh button to monitor the status.","alert-info"):(j("start"),t.setUrl(c.related.inventory_source),t.get().success(function(b){v({scope:a,url:b.related.update,group_name:b.summary_fields.group.name,group_source:b.source,tree_id:c.id,group_id:c.group_id})}).error(function(b,d){j("stop"),u(a,b,d,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+c.related.inventory_source+" POST returned status: "+d})}))))},a.cancelUpdate=function(b){z({scope:a,tree_id:b})},a.toggle=function(b){x({scope:a,list:R,id:b})},a.refreshGroups=function(b,c){b&&(a.selected_tree_id=b,a.selected_group_id=c),i({scope:a,inventory_id:a.inventory_id,refresh:!0})},a.viewUpdateStatus=function(b,c){y({scope:a,tree_id:b,group_id:c})},a.deleteGroup=function(b,c){p({scope:a,tree_id:b,group_id:c,inventory_id:a.inventory_id})},a.createHost=function(){B({scope:a})},a.editInventoryProperties=function(){C({scope:a,inventory_id:a.inventory_id})},a.editHost=function(b){D({scope:a,host_id:b,inventory_id:a.inventory_id})},a.deleteHost=function(b,c){E({scope:a,host_id:b,host_name:c})},a.toggleHostEnabled=function(b,c){F({scope:a,host_id:b,external_source:c})},a.showGroupActivity=function(){var b,c,d;a.selected_group_id?(d=A({list:a.groups,key:"id",val:a.selected_tree_id}),b=J("activity_stream")+"?group__id="+a.selected_group_id,c="Showing all activities for group "+d.name):(c="Showing all activities for all "+a.inventory_name+" groups",b=J("activity_stream")+"?group__inventory__id="+a.inventory_id),I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showHostActivity=function(){var b,c;c="Showing all activities for all "+a.inventory_name+" hosts",b=J("activity_stream")+"?host__inventory__id="+a.inventory_id,I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showJobSummary=function(a){K({job_id:a})},a.showGroupHelp=function(a){var b={defn:O};a&&(b.autoShow=a.autoShow||!1),N(b)},i({scope:a,inventory_id:a.inventory_id,refresh:!1})}function JobEventsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){function y(a){var b,c,d,e,f,g="",h=!1;if(a.res){if("string"==typeof a.res)c=a.res.match(/\n/g),d=c?c.length:1,d=d>10?10:d,h=!0,g+='
\n',g+="\n",g+='\n",g+="
\n";else for(e in a.res){if(("msg"===e||"stdout"===e||"stderr"===e)&&null!==a.res[e]&&""!==a.res[e]){switch(g+='
\n",h=!0)}g=h?'\n":""}return g=a.hosts?''+a.host+"\n"+g:""===g?null:g}p("htmlTemplate");var z,A=i,B=r("jobs")+f.id+"/job_events/",C=j,D=C.inject(A,{mode:"edit"});A.base=d.path(),D.job_id=f.id,c.flashMessage=null,D.selected=[],D.expand=!0,D.parentNode="parent-event",D.childNode="child-event",D.removeSetHostLinks&&D.removeSetHostLinks(),D.removeSetHostLinks=D.$on("SetHostLinks",function(a,b){for(var c=0;c15?5:e,$('textarea[name="'+c+'"]').attr("rows",e)));break;case"module_name":case"module_args":a.event_data.res&&a.event_data.res.invocation&&(t[c]=a.event_data.res.invocation.fld)}q("stop")}).error(function(a){k(t,a,status,null,{hdr:"Error!",msg:"Failed to retrieve host: "+f.event_id+". GET status: "+status})}),t.navigateBack=function(){var a="/jobs/"+f.job_id+"/job_events";f.page&&(a+="?page="+f.page),d.url(a)},t.rawView=function(){p({event_id:t.id})}}function JobHostSummaryList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){o("htmlTemplate");var u=h,v=c.path().replace(/^\//,"").split("/")[0],w=q(v)+e.id+"/job_host_summaries/",x=i,y=x.inject(u,{mode:"edit"});u.index="hosts"===v?!1:!0,y.selected=[],"hosts"===v?(y.job_id=null,y.host_id=e.id):(y.job_id=e.id,y.host_id=null),y.RemoveSetHostLink&&y.RemoveSetHostLink(),y.RemoveSetHostLink=y.$on("setHostLink",function(a,b){for(var c=0;c0?y.jobhosts[0].summary_fields.host.name:"Host"}),e.inventory&&y.$emit("setHostLink",e.inventory))}),l({scope:y,set:"jobhosts",list:u,url:w}),m({scope:y,list:u,url:w}),e.host_name&&(y[u.iterator+"SearchField"]="host",y[u.iterator+"SearchValue"]=e.host_name,y[u.iterator+"SearchFieldLabel"]=u.fields.host.label),y.search(u.iterator),y.showEvents=function(a,b){f.setUrl(b),f.get().success(function(b){j({path:"/jobs/"+b.id,title:b.name}),c.url("/jobs/"+b.id+"/job_events/?host="+encodeURI(a))}).error(function(a,c){p(y,a,c,null,{hdr:"Error!",msg:"Failed to lookup last job: "+b+". GET status: "+c})})},y.showJob=function(a){c.path("/jobs/"+a)},y.refresh=function(){null===y.host_id&&(y.jobSearchSpin=!0,y.jobLoading=!0,t("start"),r({scope:y,set:"jobhosts",iterator:"jobhost",url:y.current_url}))}}function JobTemplatesList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){o("htmlTemplate");var y=h,z=q("job_templates"),A=i,B=c.path().replace(/^\//,"").split("/")[0],C="job_templates"===B?"edit":"select",D=A.inject(y,{mode:C});b.flashMessage=null,D.removePostRefresh&&D.removePostRefresh(),D.removePostRefresh=D.$on("PostRefresh",function(){w("stop"),$("#prompt-modal").off()}),l({scope:D,set:"job_templates",list:y,url:z}),m({scope:D,list:y,url:z}),e.name&&(D[y.iterator+"SearchField"]="name",D[y.iterator+"SearchValue"]=e.name,D[y.iterator+"SearchFieldLabel"]=y.fields.name.label),D.search(y.iterator),j(),D.showActivity=function(){x({scope:D})},D.addJobTemplate=function(){c.path(c.path()+"/add")},D.editJobTemplate=function(a){c.path(c.path()+"/"+a)},D.deleteJobTemplate=function(a,b){var c=function(){$("#prompt-modal").on("hidden.bs.modal",function(){w("start")}),$("#prompt-modal").modal("hide");var b=z+a+"/";f.setUrl(b),f.destroy().success(function(){D.search(y.iterator)}).error(function(a){w("stop"),p(D,a,status,null,{hdr:"Error!",msg:"Call to "+b+" failed. DELETE returned status: "+status})})};k({hdr:"Delete",body:"Are you sure you want to delete "+b+"?",action:c})},D.submitJob=function(a){v({scope:D,id:a})}}function JobTemplatesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w){n("htmlTemplate");var x,y,z=o("job_templates"),A=g,B=h,C=B.inject(A,{mode:"add",related:!1}),D={},E={};C.parseType="yaml",u(C),C.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],C.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],C.playbook_options=[],C.allow_callbacks="false",B.reset(),l(),t({scope:C,master:D,check_field:"allow_callbacks",default_val:!1}),s({scope:C,form:A,current_item:null,list:p,field:"inventory"}),jQuery.extend(!0,E,q),E.name="cloudcredentials",E.iterator="cloudcredential",s({url:o("credentials")+"?cloud=true",scope:C,form:A,current_item:null,list:E,field:"cloud_credential",hdr:"Select Cloud Credential"}),s({url:o("credentials")+"?kind=ssh",scope:C,form:A,current_item:null,list:q,field:"credential",hdr:"Select Machine Credential"}),x=function(a,b){var c;a!==b&&C.project&&(v("start"),c=o("projects")+C.project+"/playbooks/",i.setUrl(c),i.get().success(function(a){var b,c=[];for(b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}b&&j("Waning",b,"alert-info")}).error(function(a,b){k(C,a,b,A,{hdr:"Error!",msg:"Failed to get project "+C.project+". GET returned status: "+b})}))},C.selectPlaybookUnregister&&C.selectPlaybookUnregister(),C.selectPlaybookUnregister=C.$watch("project_name",function(a,b){x(a,b),y(a,b)}),s({scope:C,form:A,current_item:null,list:r,field:"project"}),C.formSave=function(){B.clearApiErrors(),v("start");var a,b,c={};try{if(a="json"===C.parseType?JSON.parse(C.variables):jsyaml.load(C.variables),"object"!=typeof a)throw"failed to return an object!";for(b in A.fields)"select"===A.fields[b].type&&"playbook"!==b?c[b]=C[b].value:"variables"!==b&&(c[b]=C[b]);c.extra_vars=JSON.stringify(a,void 0," "),w(c.extra_vars)&&(c.extra_vars=""),i.setUrl(z),i.post(c).success(function(){v("stop");var a=d.path().replace(/^\//,"").split("/")[0];"job_templates"===a&&m(),m(1)}).error(function(a,b){v("stop"),k(C,a,b,A,{hdr:"Error!",msg:"Failed to add new job template. POST returned status: "+b})})}catch(e){v("stop"),j("Error","Error parsing extra variables. Parser returned: "+e)}},C.formReset=function(){B.reset();for(var a in D)C[a]=D[a]}}function JobTemplatesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D){p("htmlTemplate");var E,F,G=v("job_templates"),H=h,I=g,J=H.inject(I,{mode:"edit",related:!0}),K=0,L=d.path().replace(/^\//,"").split("/")[0],M={},N=f.id,O={};J.parseType="yaml",x(J),J.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],J.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],J.playbook_options=null,J.playbook=null,H.reset(),F=function(a){var b;C(a)||(b=v("projects")+a+"/playbooks/",A("start"),i.setUrl(b),i.get().success(function(a){var b;for(J.playbook_options=[],b=0;bfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}A("stop"),b&&j("Waning",b,"alert-info")}).error(function(a,b){k(J,a,b,I,{hdr:"Error!",msg:"Failed to get project "+J.project+". GET returned status: "+b})}))},J.watchProjectUnregister&&J.watchProjectUnregister(),J.watchProjectUnregister=J.$watch("project_name",function(a,b){a!==b&&""!==b&&null!==b&&void 0!==b&&(J.playbook=null,F(J.project),E())}),J.removeJobTemplateLoadFinished&&J.removeJobTemplateLoadFinished(),J.removeJobTemplateLoadFinished=J.$on("jobTemplateLoadFinished",function(){if(K++,K>=2)for(var a in O)J.search(O[a].iterator)}),J.removeRelatedJobs&&J.removeRelatedJobs(),J.removeRelatedJobs=J.$on("relatedjobs",function(){var a,b;if(J.jobs&&J.jobs.length)for(a=0;a0)for(c=0;c/g," ");for(y in z.fields.status.searchOptions)if(z.fields.status.searchOptions[y].value===e.status){C[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[y];break}}C.search(z.iterator),j(),C.refresh=function(){x("start"),C.jobLoading=!1,u({scope:C,set:"jobs",iterator:"job",url:C.current_url})},C.refreshJob=C.refresh,C.editJob=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a)},C.viewEvents=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_events")},C.viewSummary=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_host_summaries")},C.deleteJob=function(a){f.setUrl(A+a+"/"),f.get().success(function(b){var c,d,e,g;"pending"===b.status||"running"===b.status||"waiting"===b.status?(d=b.related.cancel,e="cancel",g="Cancel Job"):(d=A+a+"/",e="delete",g="Delete Job"),c=function(){f.setUrl(d),"cancel"===e?f.post().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. POST returned status: "+b})}):f.destroy().success(function(){$("#prompt-modal").modal("hide"),C.search(z.iterator)}).error(function(a,b){$("#prompt-modal").modal("hide"),p(C,a,b,null,{hdr:"Error!",msg:"Call to "+d+" failed. DELETE returned status: "+b})})},k({hdr:g,body:"Are you sure you want to "+e+" job "+a+"?",action:c})}).error(function(a,b){p(C,a,b,null,{hdr:"Error!",msg:"Failed to get job details. GET returned status: "+b})})},C.submitJob=function(a,b){s({scope:C,id:a,template:b})}}function JobsEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){function A(a){if(null!==a&&""!==a&&void 0!==a){var b=v("projects")+a+"/playbooks/";i.setUrl(b),i.get().success(function(a){F.playbook_options=[];for(var b=0;b15?15:c}p("htmlTemplate");var C=v("jobs"),D=h,E=g,F=D.inject(E,{mode:"edit",related:!0}),G={},H=f.id,I={},J=0;D.reset(),F.job_id=H,F.parseType="yaml",F.statusSearchSpin=!1,F.jobLoadedRemove&&F.jobLoadedRemove(),F.jobLoadedRemove=F.$on("jobLoaded",function(a,b){A(F.project),F[E.name+"ReadOnly"]="new"===F.status?!1:!0,$("#forks-slider").slider("option","value",F.forks),$("#forks-slider").slider("disable"),$('input[type="checkbox"]').attr("disabled","disabled"),$('input[type="radio"]').attr("disabled","disabled"),$("#host_config_key-gen-btn").attr("disabled","disabled"),$("textarea").attr("readonly","readonly"),i.setUrl(F.template_url),i.get().success(function(a){var b=a.host_config_key?"true":"false";F.host_config_key=a.host_config_key,w({scope:F,master:G,check_field:"allow_callbacks",default_val:b}),F.callback_url=a.related?a.related.callback:"<< Job template not found >>",F.$emit("jobTemplateLoadFinished")}).error(function(){z("stop"),F.callback_url="<< Job template not found >>"}),b?(i.setUrl(b),i.get().success(function(a){F.cloud_credential_name=a.name,F.$emit("jobTemplateLoadFinished")}).error(function(a,b){k(F,a,b,null,{hdr:"Error!",msg:"Failed to related cloud credential. GET returned status: "+b})})):F.$emit("jobTemplateLoadFinished")}),F.removeJobTemplateLoadFinished&&F.removeJobTemplateLoadFinished(),F.removeJobTemplateLoadFinished=F.$on("jobTemplateLoadFinished",function(){J++,J>=3&&z("stop")}),F.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],F.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],F.playbook_options=null,F.playbook=null,z("start"),i.setUrl(C+":id/"),i.get({params:{id:H}}).success(function(a){var b,c,d,e,f,g;l();for(d in E.fields){if("variables"!==d&&null!==a[d]&&void 0!==a[d]){if("select"===E.fields[d].type)if(F[d+"_options"]&&F[d+"_options"].length>0)for(b=0;b/g," ");for(a in A.fields.scm_type.searchOptions)if(A.fields.scm_type.searchOptions[a].value===e.scm_type){F[A.iterator+"SearchSelectValue"]=A.fields.scm_type.searchOptions[a];break}}else if(e.status){F[A.iterator+"SearchValue"]=e.status,F[A.iterator+"SearchField"]="status",F[A.iterator+"SelectShow"]=!0,F[A.iterator+"SearchFieldLabel"]=A.fields.status.label,F[A.iterator+"SearchSelectOpts"]=A.fields.status.searchOptions;for(a in A.fields.status.searchOptions)if(A.fields.status.searchOptions[a].value===e.status){F[A.iterator+"SearchSelectValue"]=A.fields.status.searchOptions[a];break}}F.search(A.iterator)}),F.removeChoicesReady&&F.removeChoicesReady(),F.removeChoicesReady=F.$on("choicesReadyProject",function(){H++,2===H&&F.$emit("choicesCompleteProject")}),y({scope:F,url:B,field:"status",variable:"project_status_options",callback:"choicesReadyProject"}),y({scope:F,url:B,field:"scm_type",variable:"project_scm_type_options",callback:"choicesReadyProject"}),j(),F.showActivity=function(){x({scope:F})},F.addProject=function(){c.path(c.path()+"/add")},F.editProject=function(a){c.path(c.path()+"/"+a)},F.showSCMStatus=function(a){var b,c=F.$on("PostRefresh",function(){var d;for(b=0;bRefresh button to view the latest status.","alert-info")}).error(function(a,b){p(F,a,b,null,{hdr:"Error!",msg:"Call to "+c+" failed. GET status: "+b})})}),F.cancelUpdate=function(a,b){var c,d,e=!1;for(c=0;cRefresh button to view the latet status.","alert-info")},F.refresh=function(){w("start"),F.projectLoading=!1,v({scope:F,set:"projects",iterator:"project",url:F.current_url})},F.SCMUpdate=function(a){var b;for(b=0;bb;b++){for(d[b].match(/[A-Z]/g)?(""!==R&&R+1==b&&(y++,C++),R=b,o++):d[b].match(/[a-z]/g)?(""!==S&&S+1==b&&(z++,C++),S=b,p++):d[b].match(/[0-9]/g)?(b>0&&e-1>b&&s++,""!==T&&T+1==b&&(A++,C++),T=b,q++):d[b].match(/[^a-zA-Z0-9_]/g)&&(b>0&&e-1>b&&s++,""!==U&&U+1==b&&(B++,C++),U=b,r++),f=!1,g=0;e>g;g++)d[b]==d[g]&&b!=g&&(f=!0,x+=Math.abs(e/(g-b)));f&&(w++,v=e-w,x=Math.ceil(v?x/v:x))}for(h=0;23>h;h++)i=ib.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(D++,G++);for(h=0;8>h;h++)i=jb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(E++,G++);for(h=0;8>h;h++)i=kb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(F++,G++);o>0&&n>o&&(nScore=parseInt(nScore+2*(n-o)),V="+ "+parseInt(2*(n-o))),p>0&&n>p&&(nScore=parseInt(nScore+2*(n-p)),W="+ "+parseInt(2*(n-p))),q>0&&n>q&&(nScore=parseInt(nScore+q*P),X="+ "+parseInt(q*P)),r>0&&(nScore=parseInt(nScore+r*Q),Y="+ "+parseInt(r*Q)),s>0&&(nScore=parseInt(nScore+s*H),Z="+ "+parseInt(s*H)),(p>0||o>0)&&0===r&&0===q&&(nScore=parseInt(nScore-n),t=n,_="- "+n),0===p&&0===o&&0===r&&q>0&&(nScore=parseInt(nScore-n),u=n,ab="- "+n),w>0&&(nScore=parseInt(nScore-x),bb="- "+x),y>0&&(nScore=parseInt(nScore-y*I),cb="- "+parseInt(y*I)),z>0&&(nScore=parseInt(nScore-z*J),db="- "+parseInt(z*J)),A>0&&(nScore=parseInt(nScore-A*K),eb="- "+parseInt(A*K)),D>0&&(nScore=parseInt(nScore-D*L),fb="- "+parseInt(D*L)),E>0&&(nScore=parseInt(nScore-E*M),gb="- "+parseInt(E*M)),F>0&&(nScore=parseInt(nScore-F*N),hb="- "+parseInt(F*N)),nScore>100?nScore=100:0>nScore&&(nScore=0),k=$("#progbar"),l=$AnsibleConfig.password_strength,m=$AnsibleConfig.password_strength-15<0?0:$AnsibleConfig.password_strength-15,k.css("width",nScore+"%"),nScore>=0&&m>=nScore?(lb="Weak",k.addClass("progress-bar-danger"),k.removeClass("progress-bar-success progress-bar-warning")):nScore>m&&l>=nScore?(lb="Good",k.addClass("progress-bar-warning"),k.removeClass("progress-bar-success progress-bar-danger")):nScore>l&&(lb="Strong",k.addClass("progress-bar-success"),k.removeClass("progress-bar-warning progress-bar-danger"))}else k=$("#progbar"),k.css("width","0%"),k.removeClass("progress-bar-success progress-bar-warning");return nScore}function AdminsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){var q=h,r=o("organizations")+e.organization_id+"/users/",s=i,t="select",u=o("organizations")+e.organization_id+"/admins/";s.inject(h,{mode:t,scope:a}),p({scope:a,list:q,url:u,returnToCaller:1}),l({scope:a,set:"admins",list:q,url:r}),m({scope:a,list:q,url:r}),a.search(q.iterator),j()}function Authenticate(a,b,c,d,e,f,g,h,i,j,k){var l,m,n,o;l=function(){$("#login-username").focus()},n=k(d.sessionExpired)?a.get("sessionExpired"):d.sessionExpired,m=function(){return k(d.lastPath)?a.get("lastPath"):d.lastPath},$AnsibleConfig.debug_mode&&console&&(console.log("User session expired: "+n),console.log("Last URL: "+m())),$(".modal[aria-hidden=false]").each(function(){"login-modal"!==$(this).attr("id")&&$(this).modal("hide")}),i("stop"),$("#login-modal").modal({show:!0,keyboard:!1,backdrop:"static"}),$("#login-modal").on("shown.bs.modal",function(){l()}),o=angular.element(document.getElementById("login-modal")).scope(),o.login_username=null,o.login_password=null,o.loginForm.login_username.$setPristine(),o.loginForm.login_password.$setPristine(),"/logout"===e.path()&&f.logout(),d.userLoggedIn=!1,a.put("userLoggedIn",!1),$("#login-password").bind("keypress",function(a){var b=a.keyCode?a.keyCode:a.which;13===b&&$("#login-button").click()}),o.reset=function(){$("#login-form input").each(function(){$(this).val("")})},o.systemLogin=function(a,b){$(".api-error").empty();var c;k(a)||k(b)?h("Error!","Please provide a username and password before attempting to login.","alert-danger",l):(i("start"),f.retrieveToken(a,b).success(function(a,b){$("#login-modal").modal("hide"),c=a.token,f.setToken(a.token,a.expires),d.sessionTimer=j.init(),f.getUser().success(function(a){f.setUserInfo(a),d.user_is_superuser=a.results[0].is_superuser,f.getLicense().success(function(a){f.setLicense(a.license_info),m()?e.path(m()):e.url("/home?login=true")}).error(function(){i("stop"),h("Error","Failed to access user information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){i("stop"),h("Error","Failed to access license information. GET returned status: "+b,"alert-danger",l)})}).error(function(a,b){var c,d,e;if(i("stop"),a.non_field_errors&&0===a.non_field_errors.length)for(e in a)o[e+"Error"]=a[e][0];else a.non_field_errors&&a.non_field_errors.length>0?(c="Error",d=a.non_field_errors[0]):(c="Error",d="The login attempt failed with a status of: "+b),o.reset(),h(c,d,"alert-danger",l)}))}}function CredentialsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){o(),t("start");var v,w=h,x=q("credentials"),y=i,z=c.path().replace(/^\//,"").split("/")[0],A="credentials"===z?"edit":"select";y.inject(w,{mode:A,scope:a}),a.selected=[],a.credentialLoading=!0,v=q(z)+("users"===z?e.user_id+"/credentials/":e.team_id+"/credentials/"),"select"===A&&r({scope:a,list:w,url:v,returnToCaller:1}),a.removePostRefresh&&a.removePostRefresh(),a.removePostRefresh=a.$on("PostRefresh",function(){var b,c;for(t("stop"),$("#prompt-modal").off(),w.fields.kind.searchOptions=a.credential_kind_options,b=0;b/g," ");for(x in z.fields.status.searchOptions)if(z.fields.status.searchOptions[x].value===b.status){B[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[x];break}}if(b.source){B[z.iterator+"SearchField"]="source",B[z.iterator+"SelectShow"]=!0,B[z.iterator+"SearchSelectOpts"]=z.fields.source.searchOptions,B[z.iterator+"SearchFieldLabel"]=z.fields.source.label.replace(/ /g," ");for(x in z.fields.source.searchOptions)if(z.fields.source.searchOptions[x].value===b.source){B[z.iterator+"SearchSelectValue"]=z.fields.source.searchOptions[x];break}b.status&&(B[z.iterator+"ExtraParms"]="&inventory_source__status__icontains="+b.status)}b.has_external_source&&(B[z.iterator+"SearchField"]="has_external_source",B[z.iterator+"SearchValue"]=z.fields.has_external_source.searchValue,B[z.iterator+"InputDisable"]=!0,B[z.iterator+"SearchType"]="in",B[z.iterator+"SearchFieldLabel"]=z.fields.has_external_source.label),B.search(z.iterator),f(),B.showActivity=function(){p({scope:B})},B.editGroup=function(a,b){q({scope:B,group_id:a,inventory_id:b,groups_reload:!1})},B.viewUpdateStatus=function(a){B.groups=B.home_groups,o({scope:B,tree_id:a})},B.updateGroup=function(a){var b=w({list:B.home_groups,key:"id",val:a});b&&(u(b.source)||("updating"===b.status?s("Update in Progress","The inventory update process is currently running for group "+b.name+". Use the Refresh button to monitor the status.","alert-info"):(r("start"),t.setUrl(b.related.inventory_source),t.get().success(function(a){v({scope:B,url:a.related.update,group_name:a.summary_fields.group.name,group_source:a.source,tree_id:b.id,group_id:b.id})}).error(function(a,c){e(B,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+b.related.inventory_source+" POST returned status: "+c})}))))},B.refresh=function(){B.search(z.iterator,null,!1,!0)}}function HomeHosts(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){h("htmlTemplate");var s=d,t=c,u=i("hosts"),v=s.inject(t,{mode:"edit"});v.removePostRefresh&&v.removePostRefresh(),v.removePostRefresh=v.$on("PostRefresh",function(){for(var a=0;a0?(a.inventories[b].failed_hosts_tip=a.inventories[b].hosts_with_active_failures+(1===a.inventories[b].hosts_with_active_failures?" host":" hosts")+" with job failures. Click to view details.",a.inventories[b].failed_hosts_link="/#/inventories/"+a.inventories[b].id+"/",a.inventories[b].failed_hosts_class="true"):0===a.inventories[b].total_hosts?(a.inventories[b].failed_hosts_tip="No hosts defined. Click to add.",a.inventories[b].failed_hosts_link="/#/inventories/"+a.inventories[b].id+"/",a.inventories[b].failed_hosts_class="na"):(a.inventories[b].failed_hosts_tip=a.inventories[b].total_hosts+(a.inventories[b].total_hosts>1?" hosts":" host")+" with no job failures. Click to view details.",a.inventories[b].failed_hosts_link="/#/inventories/"+a.inventories[b].id+"/",a.inventories[b].failed_hosts_class="false"),a.inventories[b].status=a.inventories[b].inventory_sources_with_failures+" / "+a.inventories[b].total_inventory_sources,a.inventories[b].inventory_sources_with_failures>0?(a.inventories[b].status_tip=a.inventories[b].inventory_sources_with_failures+" cloud "+(1===a.inventories[b].inventory_sources_with_failures?"source":"sources")+" with failures. Click to view details.",a.inventories[b].status_link="/#/inventories/"+a.inventories[b].id+"/",a.inventories[b].status_class="failed"):0===a.inventories[b].total_inventory_sources?(a.inventories[b].status_tip="Not synced with a cloud source. Click to edit.",a.inventories[b].status_link="/#/inventories/"+a.inventories[b].id+"/",a.inventories[b].status_class="na"):(a.inventories[b].status_tip=a.inventories[b].total_inventory_sources+" cloud "+(a.inventories[b].total_inventory_sources>1?"sources":"source")+" with no failures. Click to view details.",a.inventories[b].status_link="/#/inventories/"+a.inventories[b].id+"/",a.inventories[b].status_class="successful")}),a.removeRefreshInventories&&a.removeRefreshInventories(),a.removeRefreshInventories=a.$on("RefreshInventories",function(){a.search(u.iterator)}),a.showActivity=function(){s({scope:a})},a.editInventoryProperties=function(b){t({scope:a,inventory_id:b})},a.addInventory=function(){c.path(c.path()+"/add")},a.editInventory=function(a){c.path(c.path()+"/"+a)},a.deleteInventory=function(b,c){var d=function(){var c=v+b+"/";$("#prompt-modal").on("hidden.bs.modal",function(){r("start")}),$("#prompt-modal").modal("hide"),f.setUrl(c),f.destroy().success(function(){a.search(u.iterator)}).error(function(b,d){r("stop"),p(a,b,d,null,{hdr:"Error!",msg:"Call to "+c+" failed. DELETE returned status: "+d})})};k({hdr:"Delete",body:"Are you sure you want to delete "+c+"?",action:d})},a.lookupOrganization=function(a){f.setUrl(q("organizations")+a+"/"),f.get().success(function(a){return a.name})},a.viewJobs=function(a){c.url("/jobs/?inventory__int="+a)},a.viewFailedJobs=function(a){c.url("/jobs/?inventory__int="+a+"&status=failed")}}function InventoriesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v){n();var w=t("inventory"),x=g,y=h;x.well=!0,x.formLabelSize=null,x.formFieldSize=null,y.inject(x,{mode:"add",related:!1,scope:a}),a.inventoryParseType="yaml",y.reset(),l(),u(a,"inventory_variables","inventoryParseType"),s({scope:a,form:x,current_item:f.organization_id?f.organization_id:null,list:p,field:"organization"}),a.formSave=function(){y.clearApiErrors(),v("start");try{var b,c,e;if(c="json"===a.inventoryParseType?JSON.parse(a.inventory_variables):jsyaml.load(a.inventory_variables),"object"!=typeof c)throw"failed to return an object!";e={};for(b in x.fields)"inventory_variables"!==b&&(x.fields[b].realName?e[x.fields[b].realName]=a[b]:e[b]=a[b]);i.setUrl(w),i.post(e).success(function(b){var e=b.id;a.inventory_variables?(i.setUrl(b.related.variable_data),i.put(c).success(function(){v("stop"),d.path("/inventories/"+e+"/")}).error(function(b,c){k(a,b,c,null,{hdr:"Error!",msg:"Failed to add inventory varaibles. PUT returned status: "+c})})):(v("stop"),d.path("/inventories/"+e+"/"))}).error(function(b,c){k(a,b,c,x,{hdr:"Error!",msg:"Failed to add new inventory. Post returned status: "+c})})}catch(f){v("stop"),j("Error","Error parsing inventory variables. Parser returned: "+f)}},a.formReset=function(){y.reset()}}function InventoriesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P){f();var Q=e,R=g;a.inventory_id=c.inventory_id,r({path:b.path(),title:"{{ inventory_name }}"}),a.removeGroupTreeLoaded&&a.removeGroupTreeLoaded(),a.removeGroupTreeLoaded=a.$on("GroupTreeLoaded",function(b,c,e){var f,g;f=angular.element(document.getElementById("breadcrumbs")),f.html(q({list:R,mode:"edit"})),d(f)(a),Q.inject(R,{mode:"edit",id:"groups-container",breadCrumbs:!1,searchSize:"col-lg-5 col-md-5 col-sm-5"}),a.groups=e,a.inventory_name=c,a.groups.length>0?(a.selected_tree_id=a.groups[0].id,a.selected_group_id=a.groups[0].group_id,a.groups[0].selected_class="selected",a.groups[0].active_class="active-row",a.selected_group_name=a.groups[0].name):(a.selected_tree_id=null,a.selected_group_id=null),a.show_failures=!1,l({scope:a,inventory_id:a.inventory_id,tree_id:a.selected_tree_id,group_id:a.selected_group_id}),setTimeout(function(){$("#groups_table .name-column").each(function(){var a,b,c,d,e;a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%",$(this).find(".group-name").css({width:e})}),L("#groups_table .group-name a"),L("#hosts_table .host-name a")},2500),M(),g=P("inventoryAutoHelp"),"off"!==g&&a.autoShowGroupHelp&&a.showGroupHelp({autoShow:!0})}),a.removeGroupTreeRefreshed&&a.removeGroupTreeRefreshed(),a.removeGroupTreeRefreshed=a.$on("GroupTreeRefreshed",function(){setTimeout(function(){L("#groups_table .group-name a")},2500),a.showHosts(a.selected_tree_id,a.selected_group_id,!1)}),a.removeGroupDeleteCompleted&&a.removeGroupDeleteCompleted(),a.removeGroupDeleteCompleted=a.$on("GroupDeleteCompleted",function(){a.selected_tree_id=1,a.selected_group_id=null,i({scope:a,inventory_id:a.inventory_id,refresh:!0})}),a.removeCopMoveGroup&&a.removeCopyMoveGroup(),a.removeCopyMoveGroup=a.$on("CopyMoveGroup",function(b,c,d){G({scope:a,target_tree_id:d,inbound_tree_id:c})}),a.removeCopMoveHost&&a.removeCopyMoveHost(),a.removeCopyMoveHost=a.$on("CopyMoveHost",function(b,c,d){H({scope:a,target_tree_id:c,host_id:d})}),a.showHosts=function(b,c,d){if(null!==b){j("start"),a.selected_tree_id=b,a.selected_group_id=c,a.hosts=[],a.show_failures=d;for(var e=0;e"+c.name+". Use the Refresh button to monitor the status.","alert-info"):(j("start"),t.setUrl(c.related.inventory_source),t.get().success(function(b){v({scope:a,url:b.related.update,group_name:b.summary_fields.group.name,group_source:b.source,tree_id:c.id,group_id:c.group_id})}).error(function(b,d){j("stop"),u(a,b,d,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+c.related.inventory_source+" POST returned status: "+d})}))))},a.cancelUpdate=function(b){z({scope:a,tree_id:b})},a.toggle=function(b){x({scope:a,list:R,id:b})},a.refreshGroups=function(b,c){b&&(a.selected_tree_id=b,a.selected_group_id=c),i({scope:a,inventory_id:a.inventory_id,refresh:!0})},a.viewUpdateStatus=function(b,c){y({scope:a,tree_id:b,group_id:c})},a.deleteGroup=function(b,c){p({scope:a,tree_id:b,group_id:c,inventory_id:a.inventory_id})},a.createHost=function(){B({scope:a})},a.editInventoryProperties=function(){C({scope:a,inventory_id:a.inventory_id})},a.editHost=function(b){D({scope:a,host_id:b,inventory_id:a.inventory_id})},a.deleteHost=function(b,c){E({scope:a,host_id:b,host_name:c})},a.toggleHostEnabled=function(b,c){F({scope:a,host_id:b,external_source:c})},a.showGroupActivity=function(){var b,c,d;a.selected_group_id?(d=A({list:a.groups,key:"id",val:a.selected_tree_id}),b=J("activity_stream")+"?group__id="+a.selected_group_id,c="Showing all activities for group "+d.name):(c="Showing all activities for all "+a.inventory_name+" groups",b=J("activity_stream")+"?group__inventory__id="+a.inventory_id),I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showHostActivity=function(){var b,c;c="Showing all activities for all "+a.inventory_name+" hosts",b=J("activity_stream")+"?host__inventory__id="+a.inventory_id,I({scope:a,inventory_name:a.inventory_name,url:b,title:c})},a.showJobSummary=function(a){K({job_id:a})},a.showGroupHelp=function(a){var b={defn:O};a&&(b.autoShow=a.autoShow||!1),N(b)},i({scope:a,inventory_id:a.inventory_id,refresh:!1})}function JobEventsList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){function y(a){var b,c,d,e,f,g="",h=!1;if(a.res){if("string"==typeof a.res)c=a.res.match(/\n/g),d=c?c.length:1,d=d>10?10:d,h=!0,g+='
\n',g+="\n",g+='\n",g+="
\n";else for(e in a.res){if(("msg"===e||"stdout"===e||"stderr"===e)&&null!==a.res[e]&&""!==a.res[e]){switch(g+='
\n",h=!0)}g=h?'\n":""}return g=a.hosts?''+a.host+"\n"+g:""===g?null:g}p();var z,A=i,B=r("jobs")+f.id+"/job_events/",C=j;C.inject(A,{mode:"edit",scope:b}),A.base=d.path(),b.job_id=f.id,c.flashMessage=null,b.selected=[],b.expand=!0,b.parentNode="parent-event",b.childNode="child-event",b.removeSetHostLinks&&b.removeSetHostLinks(),b.removeSetHostLinks=b.$on("SetHostLinks",function(a,c){for(var d=0;d15?5:g,$('textarea[name="'+d+'"]').attr("rows",g)));break;case"module_name":case"module_args":b.event_data.res&&b.event_data.res.invocation&&(a[d]=b.event_data.res.invocation.fld)}q("stop")}).error(function(b){k(a,b,status,null,{hdr:"Error!",msg:"Failed to retrieve host: "+f.event_id+". GET status: "+status})}),a.navigateBack=function(){var a="/jobs/"+f.job_id+"/job_events";f.page&&(a+="?page="+f.page),d.url(a)},a.rawView=function(){p({event_id:a.id})}}function JobHostSummaryList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){o();var u=h,v=c.path().replace(/^\//,"").split("/")[0],w=q(v)+e.id+"/job_host_summaries/",x=i,y=x.inject(u,{mode:"edit"});u.index="hosts"===v?!1:!0,a.selected=[],"hosts"===v?(a.job_id=null,a.host_id=e.id):(a.job_id=e.id,a.host_id=null),a.RemoveSetHostLink&&a.RemoveSetHostLink(),a.RemoveSetHostLink=a.$on("setHostLink",function(b,c){for(var d=0;d0?a.jobhosts[0].summary_fields.host.name:"Host"}),e.inventory&&a.$emit("setHostLink",e.inventory))}),l({scope:y,set:"jobhosts",list:u,url:w}),m({scope:y,list:u,url:w}),e.host_name&&(y[u.iterator+"SearchField"]="host",y[u.iterator+"SearchValue"]=e.host_name,y[u.iterator+"SearchFieldLabel"]=u.fields.host.label),a.search(u.iterator),a.showEvents=function(a,b){f.setUrl(b),f.get().success(function(b){j({path:"/jobs/"+b.id,title:b.name}),c.url("/jobs/"+b.id+"/job_events/?host="+encodeURI(a))}).error(function(a,c){p(y,a,c,null,{hdr:"Error!",msg:"Failed to lookup last job: "+b+". GET status: "+c})})},a.showJob=function(a){c.path("/jobs/"+a)},a.refresh=function(){null===a.host_id&&(a.jobSearchSpin=!0,a.jobLoading=!0,t("start"),r({scope:y,set:"jobhosts",iterator:"jobhost",url:a.current_url}))}}function JobTemplatesList(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){o();var y=h,z=q("job_templates"),A=i,B=c.path().replace(/^\//,"").split("/")[0],C="job_templates"===B?"edit":"select";A.inject(y,{mode:C,scope:a}),b.flashMessage=null,a.removePostRefresh&&a.removePostRefresh(),a.removePostRefresh=a.$on("PostRefresh",function(){w("stop"),$("#prompt-modal").off()}),l({scope:a,set:"job_templates",list:y,url:z}),m({scope:a,list:y,url:z}),e.name&&(a[y.iterator+"SearchField"]="name",a[y.iterator+"SearchValue"]=e.name,a[y.iterator+"SearchFieldLabel"]=y.fields.name.label),a.search(y.iterator),j(),a.showActivity=function(){x({scope:a})},a.addJobTemplate=function(){c.path(c.path()+"/add")},a.editJobTemplate=function(a){c.path(c.path()+"/"+a)},a.deleteJobTemplate=function(b,c){var d=function(){$("#prompt-modal").on("hidden.bs.modal",function(){w("start")}),$("#prompt-modal").modal("hide");var c=z+b+"/";f.setUrl(c),f.destroy().success(function(){a.search(y.iterator)}).error(function(b){w("stop"),p(a,b,status,null,{hdr:"Error!",msg:"Call to "+c+" failed. DELETE returned status: "+status})})};k({hdr:"Delete",body:"Are you sure you want to delete "+c+"?",action:d})},a.submitJob=function(b){v({scope:a,id:b})}}function JobTemplatesAdd(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w){n();var x,y,z=o("job_templates"),A=g,B=h,C={},D={};B.inject(A,{mode:"add",related:!1,scope:a}),a.parseType="yaml",u(a),a.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],a.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],a.playbook_options=[],a.allow_callbacks="false",B.reset(),l(),t({scope:a,master:C,check_field:"allow_callbacks",default_val:!1}),s({scope:a,form:A,current_item:null,list:p,field:"inventory"}),jQuery.extend(!0,D,q),D.name="cloudcredentials",D.iterator="cloudcredential",s({url:o("credentials")+"?cloud=true",scope:a,form:A,current_item:null,list:D,field:"cloud_credential",hdr:"Select Cloud Credential"}),s({url:o("credentials")+"?kind=ssh",scope:a,form:A,current_item:null,list:q,field:"credential",hdr:"Select Machine Credential"}),x=function(b,c){var d;b!==c&&a.project&&(v("start"),d=o("projects")+a.project+"/playbooks/",i.setUrl(d),i.get().success(function(b){var c,d=[];for(c=0;cfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}b&&j("Waning",b,"alert-info")}).error(function(b,c){k(a,b,c,A,{hdr:"Error!",msg:"Failed to get project "+a.project+". GET returned status: "+c})}))},a.selectPlaybookUnregister&&a.selectPlaybookUnregister(),a.selectPlaybookUnregister=a.$watch("project_name",function(a,b){x(a,b),y(a,b)}),s({scope:a,form:A,current_item:null,list:r,field:"project"}),a.formSave=function(){B.clearApiErrors(),v("start");var b,c,e={};try{if(b="json"===a.parseType?JSON.parse(a.variables):jsyaml.load(a.variables),"object"!=typeof b)throw"failed to return an object!";for(c in A.fields)"select"===A.fields[c].type&&"playbook"!==c?e[c]=a[c].value:"variables"!==c&&(e[c]=a[c]);e.extra_vars=JSON.stringify(b,void 0," "),w(e.extra_vars)&&(e.extra_vars=""),i.setUrl(z),i.post(e).success(function(){v("stop");var a=d.path().replace(/^\//,"").split("/")[0];"job_templates"===a&&m(),m(1)}).error(function(b,c){v("stop"),k(a,b,c,A,{hdr:"Error!",msg:"Failed to add new job template. POST returned status: "+c})})}catch(f){v("stop"),j("Error","Error parsing extra variables. Parser returned: "+f)}},a.formReset=function(){B.reset();for(var b in C)a[b]=C[b]}}function JobTemplatesEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D){p();var E,F,G=v("job_templates"),H=h,I=g,J=0,K=d.path().replace(/^\//,"").split("/")[0],L={},M=f.id,N={};H.inject(I,{mode:"edit",related:!0,scope:a}),a.parseType="yaml",x(a),a.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],a.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],a.playbook_options=null,a.playbook=null,H.reset(),F=function(b){var c;C(b)||(c=v("projects")+b+"/playbooks/",A("start"),i.setUrl(c),i.get().success(function(b){var c;for(a.playbook_options=[],c=0;cfailed status. Review the project's SCM settings and run an update before adding it to a template.";break;case"never updated":b="The selected project has a never updated status. You will need to run a successful update in order to selected a playbook. Without a valid playbook you will not be able to save this template.";break;case"missing":b="The selected project has a status of missing. Please check the server and make sure the directory exists and file permissions are set correctly."}A("stop"),b&&j("Waning",b,"alert-info")}).error(function(b,c){k(a,b,c,I,{hdr:"Error!",msg:"Failed to get project "+a.project+". GET returned status: "+c})}))},a.watchProjectUnregister&&a.watchProjectUnregister(),a.watchProjectUnregister=a.$watch("project_name",function(b,c){b!==c&&""!==c&&null!==c&&void 0!==c&&(a.playbook=null,F(a.project),E())}),a.removeJobTemplateLoadFinished&&a.removeJobTemplateLoadFinished(),a.removeJobTemplateLoadFinished=a.$on("jobTemplateLoadFinished",function(){if(J++,J>=2)for(var b in N)a.search(N[b].iterator)}),a.removeRelatedJobs&&a.removeRelatedJobs(),a.removeRelatedJobs=a.$on("relatedjobs",function(){var b,c;if(a.jobs&&a.jobs.length)for(b=0;b0)for(d=0;d/g," ");for(y in z.fields.status.searchOptions)if(z.fields.status.searchOptions[y].value===e.status){a[z.iterator+"SearchSelectValue"]=z.fields.status.searchOptions[y];break}}a.search(z.iterator),j(),a.refresh=function(){x("start"),a.jobLoading=!1,u({scope:a,set:"jobs",iterator:"job",url:a.current_url})},a.refreshJob=a.refresh,a.editJob=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a)},a.viewEvents=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_events")},a.viewSummary=function(a,b){j({path:"/jobs/"+a,title:a+" - "+b}),c.path(c.path()+"/"+a+"/job_host_summaries")},a.deleteJob=function(b){f.setUrl(A+b+"/"),f.get().success(function(c){var d,e,g,h;"pending"===c.status||"running"===c.status||"waiting"===c.status?(e=c.related.cancel,g="cancel",h="Cancel Job"):(e=A+b+"/",g="delete",h="Delete Job"),d=function(){f.setUrl(e),"cancel"===g?f.post().success(function(){$("#prompt-modal").modal("hide"),a.search(z.iterator)}).error(function(b,c){$("#prompt-modal").modal("hide"),p(a,b,c,null,{hdr:"Error!",msg:"Call to "+e+" failed. POST returned status: "+c})}):f.destroy().success(function(){$("#prompt-modal").modal("hide"),a.search(z.iterator)}).error(function(b,c){$("#prompt-modal").modal("hide"),p(a,b,c,null,{hdr:"Error!",msg:"Call to "+e+" failed. DELETE returned status: "+c})})},k({hdr:h,body:"Are you sure you want to "+g+" job "+b+"?",action:d})}).error(function(b,c){p(a,b,c,null,{hdr:"Error!",msg:"Failed to get job details. GET returned status: "+c})})},a.submitJob=function(b,c){s({scope:a,id:b,template:c})}}function JobsEdit(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){function A(b){if(null!==b&&""!==b&&void 0!==b){var c=v("projects")+b+"/playbooks/";i.setUrl(c),i.get().success(function(b){a.playbook_options=[];for(var c=0;c15?15:c}p();var C=v("jobs"),D=h,E=g,F={},G=f.id,H={},I=0;D.inject(E,{mode:"edit",related:!0,scope:a}),D.reset(),a.job_id=G,a.parseType="yaml",a.statusSearchSpin=!1,a.jobLoadedRemove&&a.jobLoadedRemove(),a.jobLoadedRemove=a.$on("jobLoaded",function(b,c){A(a.project),a[E.name+"ReadOnly"]="new"===a.status?!1:!0,$("#forks-slider").slider("option","value",a.forks),$("#forks-slider").slider("disable"),$('input[type="checkbox"]').attr("disabled","disabled"),$('input[type="radio"]').attr("disabled","disabled"),$("#host_config_key-gen-btn").attr("disabled","disabled"),$("textarea").attr("readonly","readonly"),i.setUrl(a.template_url),i.get().success(function(b){var c=b.host_config_key?"true":"false";a.host_config_key=b.host_config_key,w({scope:a,master:F,check_field:"allow_callbacks",default_val:c}),a.callback_url=b.related?b.related.callback:"<< Job template not found >>",a.$emit("jobTemplateLoadFinished")}).error(function(){z("stop"),a.callback_url="<< Job template not found >>"}),c?(i.setUrl(c),i.get().success(function(b){a.cloud_credential_name=b.name,a.$emit("jobTemplateLoadFinished")}).error(function(b,c){k(a,b,c,null,{hdr:"Error!",msg:"Failed to related cloud credential. GET returned status: "+c})})):a.$emit("jobTemplateLoadFinished")}),a.removeJobTemplateLoadFinished&&a.removeJobTemplateLoadFinished(),a.removeJobTemplateLoadFinished=a.$on("jobTemplateLoadFinished",function(){I++,I>=3&&z("stop")}),a.job_type_options=[{value:"run",label:"Run"},{value:"check",label:"Check"}],a.verbosity_options=[{value:"0",label:"Default"},{value:"1",label:"Verbose"},{value:"3",label:"Debug"}],a.playbook_options=null,a.playbook=null,z("start"),i.setUrl(C+":id/"),i.get({params:{id:G}}).success(function(b){var c,d,e,f,g,h;l();for(e in E.fields){if("variables"!==e&&null!==b[e]&&void 0!==b[e]){if("select"===E.fields[e].type)if(a[e+"_options"]&&a[e+"_options"].length>0)for(c=0;c/g," ");for(b in A.fields.scm_type.searchOptions)if(A.fields.scm_type.searchOptions[b].value===e.scm_type){a[A.iterator+"SearchSelectValue"]=A.fields.scm_type.searchOptions[b];break}}else if(e.status){a[A.iterator+"SearchValue"]=e.status,a[A.iterator+"SearchField"]="status",a[A.iterator+"SelectShow"]=!0,a[A.iterator+"SearchFieldLabel"]=A.fields.status.label,a[A.iterator+"SearchSelectOpts"]=A.fields.status.searchOptions;for(b in A.fields.status.searchOptions)if(A.fields.status.searchOptions[b].value===e.status){a[A.iterator+"SearchSelectValue"]=A.fields.status.searchOptions[b];break}}a.search(A.iterator)}),a.removeChoicesReady&&a.removeChoicesReady(),a.removeChoicesReady=a.$on("choicesReadyProject",function(){G++,2===G&&a.$emit("choicesCompleteProject")}),y({scope:a,url:B,field:"status",variable:"project_status_options",callback:"choicesReadyProject"}),y({scope:a,url:B,field:"scm_type",variable:"project_scm_type_options",callback:"choicesReadyProject"}),j(),a.showActivity=function(){x({scope:a})},a.addProject=function(){c.path(c.path()+"/add")},a.editProject=function(a){c.path(c.path()+"/"+a)},a.showSCMStatus=function(b){var c,d=a.$on("PostRefresh",function(){var e;for(c=0;cRefresh button to view the latest status.","alert-info")}).error(function(b,c){p(a,b,c,null,{hdr:"Error!",msg:"Call to "+d+" failed. GET status: "+c})})}),a.cancelUpdate=function(b,c){var d,e,h=!1;for(d=0;dRefresh button to view the latet status.","alert-info")},a.refresh=function(){w("start"),a.projectLoading=!1,v({scope:a,set:"projects",iterator:"project",url:a.current_url})},a.SCMUpdate=function(b){var c;for(c=0;cb;b++){for(d[b].match(/[A-Z]/g)?(""!==R&&R+1==b&&(y++,C++),R=b,o++):d[b].match(/[a-z]/g)?(""!==S&&S+1==b&&(z++,C++),S=b,p++):d[b].match(/[0-9]/g)?(b>0&&e-1>b&&s++,""!==T&&T+1==b&&(A++,C++),T=b,q++):d[b].match(/[^a-zA-Z0-9_]/g)&&(b>0&&e-1>b&&s++,""!==U&&U+1==b&&(B++,C++),U=b,r++),f=!1,g=0;e>g;g++)d[b]==d[g]&&b!=g&&(f=!0,x+=Math.abs(e/(g-b)));f&&(w++,v=e-w,x=Math.ceil(v?x/v:x))}for(h=0;23>h;h++)i=ib.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(D++,G++);for(h=0;8>h;h++)i=jb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(E++,G++);for(h=0;8>h;h++)i=kb.substring(h,parseInt(h+3)),j=i.strReverse(),(-1!=a.toLowerCase().indexOf(i)||-1!=a.toLowerCase().indexOf(j))&&(F++,G++);o>0&&n>o&&(nScore=parseInt(nScore+2*(n-o)),V="+ "+parseInt(2*(n-o))),p>0&&n>p&&(nScore=parseInt(nScore+2*(n-p)),W="+ "+parseInt(2*(n-p))),q>0&&n>q&&(nScore=parseInt(nScore+q*P),X="+ "+parseInt(q*P)),r>0&&(nScore=parseInt(nScore+r*Q),Y="+ "+parseInt(r*Q)),s>0&&(nScore=parseInt(nScore+s*H),Z="+ "+parseInt(s*H)),(p>0||o>0)&&0===r&&0===q&&(nScore=parseInt(nScore-n),t=n,_="- "+n),0===p&&0===o&&0===r&&q>0&&(nScore=parseInt(nScore-n),u=n,ab="- "+n),w>0&&(nScore=parseInt(nScore-x),bb="- "+x),y>0&&(nScore=parseInt(nScore-y*I),cb="- "+parseInt(y*I)),z>0&&(nScore=parseInt(nScore-z*J),db="- "+parseInt(z*J)),A>0&&(nScore=parseInt(nScore-A*K),eb="- "+parseInt(A*K)),D>0&&(nScore=parseInt(nScore-D*L),fb="- "+parseInt(D*L)),E>0&&(nScore=parseInt(nScore-E*M),gb="- "+parseInt(E*M)),F>0&&(nScore=parseInt(nScore-F*N),hb="- "+parseInt(F*N)),nScore>100?nScore=100:0>nScore&&(nScore=0),k=$("#progbar"),l=$AnsibleConfig.password_strength,m=$AnsibleConfig.password_strength-15<0?0:$AnsibleConfig.password_strength-15,k.css("width",nScore+"%"),nScore>=0&&m>=nScore?(lb="Weak",k.addClass("progress-bar-danger"),k.removeClass("progress-bar-success progress-bar-warning")):nScore>m&&l>=nScore?(lb="Good",k.addClass("progress-bar-warning"),k.removeClass("progress-bar-success progress-bar-danger")):nScore>l&&(lb="Strong",k.addClass("progress-bar-success"),k.removeClass("progress-bar-warning progress-bar-danger"))}else k=$("#progbar"),k.css("width","0%"),k.removeClass("progress-bar-success progress-bar-warning");return nScore}var urlPrefix=$basePath;angular.module("ansible",["ngRoute","ngSanitize","ngCookies","RestServices","AuthService","Utilities","OrganizationFormDefinition","UserFormDefinition","FormGenerator","OrganizationListDefinition","UserListDefinition","UserHelper","ListGenerator","PromptDialog","ApiLoader","RelatedSearchHelper","SearchHelper","PaginationHelpers","RefreshHelper","AdminListDefinition","AWDirectives","InventoriesListDefinition","InventoryFormDefinition","InventoryHelper","InventoryGroupsDefinition","InventoryHostsDefinition","HostsHelper","AWFilters","HostFormDefinition","HostListDefinition","GroupFormDefinition","GroupListDefinition","GroupsHelper","TeamsListDefinition","TeamFormDefinition","TeamHelper","CredentialsListDefinition","CredentialFormDefinition","LookUpHelper","JobTemplatesListDefinition","JobTemplateFormDefinition","JobSubmissionHelper","ProjectsListDefinition","ProjectFormDefinition","ProjectStatusDefinition","ProjectsHelper","PermissionFormDefinition","PermissionListDefinition","PermissionsHelper","JobsListDefinition","JobFormDefinition","JobEventsListDefinition","JobEventDataDefinition","JobEventsFormDefinition","JobHostDefinition","JobSummaryDefinition","ParseHelper","ChildrenHelper","EventsHelper","ProjectPathHelper","md5Helper","AccessHelper","SelectionHelper","License","HostGroupsFormDefinition","JobStatusWidget","InventorySyncStatusWidget","SCMSyncStatusWidget","ObjectCountWidget","StreamWidget","JobsHelper","InventoryGroupsHelpDefinition","InventoryTree","CredentialsHelper","TimerService","StreamListDefinition","HomeGroupListDefinition","HomeHostListDefinition","ActivityDetailDefinition"]).config(["$routeProvider",function(a){a.when("/jobs",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsListCtrl"}).when("/jobs/:id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsEdit"}).when("/jobs/:id/job_events",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsList"}).when("/jobs/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/jobs/:job_id/job_events/:event_id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsEdit"}).when("/job_templates",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesList"}).when("/job_templates/add",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesAdd"}).when("/job_templates/:id",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesEdit"}).when("/projects",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsList"}).when("/projects/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsAdd"}).when("/projects/:id",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsEdit"}).when("/projects/:project_id/organizations",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsList"}).when("/projects/:project_id/organizations/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsAdd"}).when("/hosts/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/inventories",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesList"}).when("/inventories/add",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesAdd"}).when("/inventories/:inventory_id",{templateUrl:urlPrefix+"partials/inventory-edit.html",controller:"InventoriesEdit"}).when("/organizations",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsList"}).when("/organizations/add",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsAdd"}).when("/organizations/:organization_id",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsEdit"}).when("/organizations/:organization_id/admins",{templateUrl:urlPrefix+"partials/organizations.html",controller:"AdminsList"}).when("/organizations/:organization_id/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/organizations/:organization_id/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/organizations/:organization_id/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/teams",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsList"}).when("/teams/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsAdd"}).when("/teams/:team_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsEdit"}).when("/teams/:team_id/permissions/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsAdd"}).when("/teams/:team_id/permissions",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsList"}).when("/teams/:team_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsEdit"}).when("/teams/:team_id/users",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersList"}).when("/teams/:team_id/users/:user_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersEdit"}).when("/teams/:team_id/projects",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsList"}).when("/teams/:team_id/projects/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsAdd"}).when("/teams/:team_id/projects/:project_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsEdit"}).when("/teams/:team_id/credentials",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsList"}).when("/teams/:team_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:team_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/credentials",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsList"}).when("/credentials/add",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsAdd"}).when("/credentials/:credential_id",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsEdit"}).when("/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/users/:user_id/credentials",{templateUrl:urlPrefix+"partials/users.html",controller:"CredentialsList"}).when("/users/:user_id/permissions/add",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsAdd"}).when("/users/:user_id/permissions",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsList"}).when("/users/:user_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsEdit"}).when("/users/:user_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:user_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/login",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/logout",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/home",{templateUrl:urlPrefix+"partials/home.html",controller:"Home"}).when("/home/groups",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeGroups"}).when("/home/hosts",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeHosts"}).otherwise({redirectTo:"/home"})}]).run(["$cookieStore","$rootScope","CheckLicense","$location","Authorization","LoadBasePaths","ViewLicense","Timer","ClearScope","HideStream",function(a,b,c,d,e,f,g,h,i,j){f(),b.breadcrumbs=[],b.crumbCache=[],b.sessionTimer=h.init(),b.$on("$routeChangeStart",function(f,g){$("#stream-container").is(":visible")&&j(),/^\/(login|logout)/.test(d.path())||(b.lastPath=d.path(),a.put("lastPath",d.path())),e.isUserLoggedIn()===!1?g.templateUrl!==urlPrefix+"partials/login.html"&&d.path("/login"):b.sessionTimer.isExpired()?g.templateUrl!==urlPrefix+"partials/login.html"&&(b.sessionTimer.expireSession(),d.path("/login")):((void 0===b.current_user||null===b.current_user)&&e.restoreUserInfo(),c());var h=d.path().replace(/^\//,"").split("/")[0];""===h?h="home":h.replace(/\_/g," "),$('.nav-tabs a[href="#'+h+'"]').tab("show")}),e.getToken()?b.user_is_superuser=e.getUserInfo("is_superuser"):(b.sessionExpired=!1,a.put("sessionExpired",!1),d.path("/login"));var k=d.path().replace(/^\//,"").split("/")[0];""===k?(k="home",d.path("/home")):k.replace(/\_/g," "),$('.nav-tabs a[href="#'+k+'"]').tab("show"),b.viewCurrentUser=function(){d.path("/users/"+b.current_user.id)},b.viewLicense=function(){g()}}]);var urlPrefix=$basePath;angular.module("ansible",["RestServices","AuthService","Utilities","OrganizationFormDefinition","UserFormDefinition","FormGenerator","OrganizationListDefinition","UserListDefinition","UserHelper","ListGenerator","PromptDialog","ApiLoader","RelatedSearchHelper","SearchHelper","PaginationHelpers","RefreshHelper","AdminListDefinition","AWDirectives","InventoriesListDefinition","InventoryFormDefinition","InventoryHelper","InventoryGroupsDefinition","InventoryHostsDefinition","HostsHelper","AWFilters","HostFormDefinition","HostListDefinition","GroupFormDefinition","GroupListDefinition","GroupsHelper","TeamsListDefinition","TeamFormDefinition","TeamHelper","CredentialsListDefinition","CredentialFormDefinition","LookUpHelper","JobTemplatesListDefinition","JobTemplateFormDefinition","JobSubmissionHelper","ProjectsListDefinition","ProjectFormDefinition","ProjectStatusDefinition","ProjectsHelper","PermissionFormDefinition","PermissionListDefinition","PermissionsHelper","JobsListDefinition","JobFormDefinition","JobEventsListDefinition","JobEventDataDefinition","JobEventsFormDefinition","JobHostDefinition","JobSummaryDefinition","ParseHelper","ChildrenHelper","EventsHelper","ProjectPathHelper","md5Helper","AccessHelper","SelectionHelper","License","HostGroupsFormDefinition","JobStatusWidget","InventorySyncStatusWidget","SCMSyncStatusWidget","ObjectCountWidget","StreamWidget","JobsHelper","InventoryGroupsHelpDefinition","InventoryTree","CredentialsHelper","TimerService","StreamListDefinition","HomeGroupListDefinition","HomeHostListDefinition","ActivityDetailDefinition"]).config(["$routeProvider",function(a){a.when("/jobs",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsListCtrl"}).when("/jobs/:id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsEdit"}).when("/jobs/:id/job_events",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsList"}).when("/jobs/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/jobs/:job_id/job_events/:event_id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsEdit"}).when("/job_templates",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesList"}).when("/job_templates/add",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesAdd"}).when("/job_templates/:id",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesEdit"}).when("/projects",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsList"}).when("/projects/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsAdd"}).when("/projects/:id",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsEdit"}).when("/projects/:project_id/organizations",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsList"}).when("/projects/:project_id/organizations/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsAdd"}).when("/hosts/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/inventories",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesList"}).when("/inventories/add",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesAdd"}).when("/inventories/:inventory_id",{templateUrl:urlPrefix+"partials/inventory-edit.html",controller:"InventoriesEdit"}).when("/organizations",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsList"}).when("/organizations/add",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsAdd"}).when("/organizations/:organization_id",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsEdit"}).when("/organizations/:organization_id/admins",{templateUrl:urlPrefix+"partials/organizations.html",controller:"AdminsList"}).when("/organizations/:organization_id/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/organizations/:organization_id/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/organizations/:organization_id/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/teams",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsList"}).when("/teams/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsAdd"}).when("/teams/:team_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsEdit"}).when("/teams/:team_id/permissions/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsAdd"}).when("/teams/:team_id/permissions",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsList"}).when("/teams/:team_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsEdit"}).when("/teams/:team_id/users",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersList"}).when("/teams/:team_id/users/:user_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersEdit"}).when("/teams/:team_id/projects",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsList"}).when("/teams/:team_id/projects/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsAdd"}).when("/teams/:team_id/projects/:project_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsEdit"}).when("/teams/:team_id/credentials",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsList"}).when("/teams/:team_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:team_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/credentials",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsList"}).when("/credentials/add",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsAdd"}).when("/credentials/:credential_id",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsEdit"}).when("/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/users/:user_id/credentials",{templateUrl:urlPrefix+"partials/users.html",controller:"CredentialsList"}).when("/users/:user_id/permissions/add",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsAdd"}).when("/users/:user_id/permissions",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsList"}).when("/users/:user_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsEdit"}).when("/users/:user_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:user_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/login",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/logout",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/home",{templateUrl:urlPrefix+"partials/home.html",controller:"Home"}).when("/home/groups",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeGroups"}).when("/home/hosts",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeHosts"}).otherwise({redirectTo:"/home"})}]).run(["$cookieStore","$rootScope","CheckLicense","$location","Authorization","LoadBasePaths","ViewLicense","Timer","ClearScope","HideStream",function(a,b,c,d,e,f,g,h,i,j){f(),b.breadcrumbs=[],b.crumbCache=[],b.sessionTimer=h.init(),b.$on("$routeChangeStart",function(f,g){$("#stream-container").is(":visible")&&j(),/^\/(login|logout)/.test(d.path())||(b.lastPath=d.path(),a.put("lastPath",d.path())),e.isUserLoggedIn()===!1?g.templateUrl!==urlPrefix+"partials/login.html"&&d.path("/login"):b.sessionTimer.isExpired()?g.templateUrl!==urlPrefix+"partials/login.html"&&(b.sessionTimer.expireSession(),d.path("/login")):((void 0===b.current_user||null===b.current_user)&&e.restoreUserInfo(),c());var h=d.path().replace(/^\//,"").split("/")[0];""===h?h="home":h.replace(/\_/g," "),$('.nav-tabs a[href="#'+h+'"]').tab("show")}),e.getToken()?b.user_is_superuser=e.getUserInfo("is_superuser"):(b.sessionExpired=!1,a.put("sessionExpired",!1),d.path("/login"));
+var k=d.path().replace(/^\//,"").split("/")[0];""===k?(k="home",d.path("/home")):k.replace(/\_/g," "),$('.nav-tabs a[href="#'+k+'"]').tab("show"),b.viewCurrentUser=function(){d.path("/users/"+b.current_user.id)},b.viewLicense=function(){g()}}]);var urlPrefix=$basePath;angular.module("ansible",["RestServices","AuthService","Utilities","OrganizationFormDefinition","UserFormDefinition","FormGenerator","OrganizationListDefinition","UserListDefinition","UserHelper","ListGenerator","PromptDialog","ApiLoader","RelatedSearchHelper","SearchHelper","PaginationHelpers","RefreshHelper","AdminListDefinition","AWDirectives","InventoriesListDefinition","InventoryFormDefinition","InventoryHelper","InventoryGroupsDefinition","InventoryHostsDefinition","HostsHelper","AWFilters","HostFormDefinition","HostListDefinition","GroupFormDefinition","GroupListDefinition","GroupsHelper","TeamsListDefinition","TeamFormDefinition","TeamHelper","CredentialsListDefinition","CredentialFormDefinition","LookUpHelper","JobTemplatesListDefinition","JobTemplateFormDefinition","JobSubmissionHelper","ProjectsListDefinition","ProjectFormDefinition","ProjectStatusDefinition","ProjectsHelper","PermissionFormDefinition","PermissionListDefinition","PermissionsHelper","JobsListDefinition","JobFormDefinition","JobEventsListDefinition","JobEventDataDefinition","JobEventsFormDefinition","JobHostDefinition","JobSummaryDefinition","ParseHelper","ChildrenHelper","EventsHelper","ProjectPathHelper","md5Helper","AccessHelper","SelectionHelper","License","HostGroupsFormDefinition","JobStatusWidget","InventorySyncStatusWidget","SCMSyncStatusWidget","ObjectCountWidget","StreamWidget","JobsHelper","InventoryGroupsHelpDefinition","InventoryTree","CredentialsHelper","TimerService","StreamListDefinition","HomeGroupListDefinition","HomeHostListDefinition","ActivityDetailDefinition"]).config(["$routeProvider",function(a){a.when("/jobs",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsListCtrl"}).when("/jobs/:id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsEdit"}).when("/jobs/:id/job_events",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsList"}).when("/jobs/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/jobs/:job_id/job_events/:event_id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsEdit"}).when("/job_templates",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesList"}).when("/job_templates/add",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesAdd"}).when("/job_templates/:id",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesEdit"}).when("/projects",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsList"}).when("/projects/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsAdd"}).when("/projects/:id",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsEdit"}).when("/projects/:project_id/organizations",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsList"}).when("/projects/:project_id/organizations/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsAdd"}).when("/hosts/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/inventories",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesList"}).when("/inventories/add",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesAdd"}).when("/inventories/:inventory_id",{templateUrl:urlPrefix+"partials/inventory-edit.html",controller:"InventoriesEdit"}).when("/organizations",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsList"}).when("/organizations/add",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsAdd"}).when("/organizations/:organization_id",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsEdit"}).when("/organizations/:organization_id/admins",{templateUrl:urlPrefix+"partials/organizations.html",controller:"AdminsList"}).when("/organizations/:organization_id/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/organizations/:organization_id/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/organizations/:organization_id/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/teams",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsList"}).when("/teams/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsAdd"}).when("/teams/:team_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsEdit"}).when("/teams/:team_id/permissions/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsAdd"}).when("/teams/:team_id/permissions",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsList"}).when("/teams/:team_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsEdit"}).when("/teams/:team_id/users",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersList"}).when("/teams/:team_id/users/:user_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersEdit"}).when("/teams/:team_id/projects",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsList"}).when("/teams/:team_id/projects/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsAdd"}).when("/teams/:team_id/projects/:project_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsEdit"}).when("/teams/:team_id/credentials",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsList"}).when("/teams/:team_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:team_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/credentials",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsList"}).when("/credentials/add",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsAdd"}).when("/credentials/:credential_id",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsEdit"}).when("/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/users/:user_id/credentials",{templateUrl:urlPrefix+"partials/users.html",controller:"CredentialsList"}).when("/users/:user_id/permissions/add",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsAdd"}).when("/users/:user_id/permissions",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsList"}).when("/users/:user_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsEdit"}).when("/users/:user_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:user_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/login",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/logout",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/home",{templateUrl:urlPrefix+"partials/home.html",controller:"Home"}).when("/home/groups",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeGroups"}).when("/home/hosts",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeHosts"}).otherwise({redirectTo:"/home"})}]).run(["$cookieStore","$rootScope","CheckLicense","$location","Authorization","LoadBasePaths","ViewLicense","Timer","ClearScope","HideStream",function(a,b,c,d,e,f,g,h,i,j){f(),b.breadcrumbs=[],b.crumbCache=[],b.sessionTimer=h.init(),b.$on("$routeChangeStart",function(f,g){$("#stream-container").is(":visible")&&j(),/^\/(login|logout)/.test(d.path())||(b.lastPath=d.path(),a.put("lastPath",d.path())),e.isUserLoggedIn()===!1?g.templateUrl!==urlPrefix+"partials/login.html"&&d.path("/login"):b.sessionTimer.isExpired()?g.templateUrl!==urlPrefix+"partials/login.html"&&(b.sessionTimer.expireSession(),d.path("/login")):((void 0===b.current_user||null===b.current_user)&&e.restoreUserInfo(),c());var h=d.path().replace(/^\//,"").split("/")[0];""===h?h="home":h.replace(/\_/g," "),$('.nav-tabs a[href="#'+h+'"]').tab("show")}),e.getToken()?b.user_is_superuser=e.getUserInfo("is_superuser"):(b.sessionExpired=!1,a.put("sessionExpired",!1),d.path("/login"));var k=d.path().replace(/^\//,"").split("/")[0];""===k?(k="home",d.path("/home")):k.replace(/\_/g," "),$('.nav-tabs a[href="#'+k+'"]').tab("show"),b.viewCurrentUser=function(){d.path("/users/"+b.current_user.id)},b.viewLicense=function(){g()}}]);var urlPrefix=$basePath;angular.module("ansible",["RestServices","AuthService","Utilities","OrganizationFormDefinition","UserFormDefinition","FormGenerator","OrganizationListDefinition","UserListDefinition","UserHelper","ListGenerator","PromptDialog","ApiLoader","RelatedSearchHelper","SearchHelper","PaginationHelpers","RefreshHelper","AdminListDefinition","AWDirectives","InventoriesListDefinition","InventoryFormDefinition","InventoryHelper","InventoryGroupsDefinition","InventoryHostsDefinition","HostsHelper","AWFilters","HostFormDefinition","HostListDefinition","GroupFormDefinition","GroupListDefinition","GroupsHelper","TeamsListDefinition","TeamFormDefinition","TeamHelper","CredentialsListDefinition","CredentialFormDefinition","LookUpHelper","JobTemplatesListDefinition","JobTemplateFormDefinition","JobSubmissionHelper","ProjectsListDefinition","ProjectFormDefinition","ProjectStatusDefinition","ProjectsHelper","PermissionFormDefinition","PermissionListDefinition","PermissionsHelper","JobsListDefinition","JobFormDefinition","JobEventsListDefinition","JobEventDataDefinition","JobEventsFormDefinition","JobHostDefinition","JobSummaryDefinition","ParseHelper","ChildrenHelper","EventsHelper","ProjectPathHelper","md5Helper","AccessHelper","SelectionHelper","License","HostGroupsFormDefinition","JobStatusWidget","InventorySyncStatusWidget","SCMSyncStatusWidget","ObjectCountWidget","StreamWidget","JobsHelper","InventoryGroupsHelpDefinition","InventoryTree","CredentialsHelper","TimerService","StreamListDefinition","HomeGroupListDefinition","HomeHostListDefinition","ActivityDetailDefinition"]).config(["$routeProvider",function(a){a.when("/jobs",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsListCtrl"}).when("/jobs/:id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsEdit"}).when("/jobs/:id/job_events",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsList"}).when("/jobs/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/jobs/:job_id/job_events/:event_id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsEdit"}).when("/job_templates",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesList"}).when("/job_templates/add",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesAdd"}).when("/job_templates/:id",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesEdit"}).when("/projects",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsList"}).when("/projects/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsAdd"}).when("/projects/:id",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsEdit"}).when("/projects/:project_id/organizations",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsList"}).when("/projects/:project_id/organizations/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsAdd"}).when("/hosts/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/inventories",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesList"}).when("/inventories/add",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesAdd"}).when("/inventories/:inventory_id",{templateUrl:urlPrefix+"partials/inventory-edit.html",controller:"InventoriesEdit"}).when("/organizations",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsList"}).when("/organizations/add",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsAdd"}).when("/organizations/:organization_id",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsEdit"}).when("/organizations/:organization_id/admins",{templateUrl:urlPrefix+"partials/organizations.html",controller:"AdminsList"}).when("/organizations/:organization_id/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/organizations/:organization_id/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/organizations/:organization_id/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/teams",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsList"}).when("/teams/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsAdd"}).when("/teams/:team_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsEdit"}).when("/teams/:team_id/permissions/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsAdd"}).when("/teams/:team_id/permissions",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsList"}).when("/teams/:team_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsEdit"}).when("/teams/:team_id/users",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersList"}).when("/teams/:team_id/users/:user_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersEdit"}).when("/teams/:team_id/projects",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsList"}).when("/teams/:team_id/projects/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsAdd"}).when("/teams/:team_id/projects/:project_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsEdit"}).when("/teams/:team_id/credentials",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsList"}).when("/teams/:team_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:team_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/credentials",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsList"}).when("/credentials/add",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsAdd"}).when("/credentials/:credential_id",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsEdit"}).when("/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/users/:user_id/credentials",{templateUrl:urlPrefix+"partials/users.html",controller:"CredentialsList"}).when("/users/:user_id/permissions/add",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsAdd"}).when("/users/:user_id/permissions",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsList"}).when("/users/:user_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsEdit"}).when("/users/:user_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:user_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/login",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/logout",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/home",{templateUrl:urlPrefix+"partials/home.html",controller:"Home"}).when("/home/groups",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeGroups"}).when("/home/hosts",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeHosts"}).otherwise({redirectTo:"/home"})}]).run(["$cookieStore","$rootScope","CheckLicense","$location","Authorization","LoadBasePaths","ViewLicense","Timer","ClearScope","HideStream",function(a,b,c,d,e,f,g,h,i,j){f(),b.breadcrumbs=[],b.crumbCache=[],b.sessionTimer=h.init(),b.$on("$routeChangeStart",function(f,g){$("#stream-container").is(":visible")&&j(),/^\/(login|logout)/.test(d.path())||(b.lastPath=d.path(),a.put("lastPath",d.path())),e.isUserLoggedIn()===!1?g.templateUrl!==urlPrefix+"partials/login.html"&&d.path("/login"):b.sessionTimer.isExpired()?g.templateUrl!==urlPrefix+"partials/login.html"&&(b.sessionTimer.expireSession(),d.path("/login")):((void 0===b.current_user||null===b.current_user)&&e.restoreUserInfo(),c());var h=d.path().replace(/^\//,"").split("/")[0];""===h?h="home":h.replace(/\_/g," "),$('.nav-tabs a[href="#'+h+'"]').tab("show")}),e.getToken()?b.user_is_superuser=e.getUserInfo("is_superuser"):(b.sessionExpired=!1,a.put("sessionExpired",!1),d.path("/login"));var k=d.path().replace(/^\//,"").split("/")[0];""===k?(k="home",d.path("/home")):k.replace(/\_/g," "),$('.nav-tabs a[href="#'+k+'"]').tab("show"),b.viewCurrentUser=function(){d.path("/users/"+b.current_user.id)},b.viewLicense=function(){g()}}]);var urlPrefix=$basePath;angular.module("ansible",["RestServices","AuthService","Utilities","OrganizationFormDefinition","UserFormDefinition","FormGenerator","OrganizationListDefinition","UserListDefinition","UserHelper","ListGenerator","PromptDialog","ApiLoader","RelatedSearchHelper","SearchHelper","PaginationHelpers","RefreshHelper","AdminListDefinition","AWDirectives","InventoriesListDefinition","InventoryFormDefinition","InventoryHelper","InventoryGroupsDefinition","InventoryHostsDefinition","HostsHelper","AWFilters","HostFormDefinition","HostListDefinition","GroupFormDefinition","GroupListDefinition","GroupsHelper","TeamsListDefinition","TeamFormDefinition","TeamHelper","CredentialsListDefinition","CredentialFormDefinition","LookUpHelper","JobTemplatesListDefinition","JobTemplateFormDefinition","JobSubmissionHelper","ProjectsListDefinition","ProjectFormDefinition","ProjectStatusDefinition","ProjectsHelper","PermissionFormDefinition","PermissionListDefinition","PermissionsHelper","JobsListDefinition","JobFormDefinition","JobEventsListDefinition","JobEventDataDefinition","JobEventsFormDefinition","JobHostDefinition","JobSummaryDefinition","ParseHelper","ChildrenHelper","EventsHelper","ProjectPathHelper","md5Helper","AccessHelper","SelectionHelper","License","HostGroupsFormDefinition","JobStatusWidget","InventorySyncStatusWidget","SCMSyncStatusWidget","ObjectCountWidget","StreamWidget","JobsHelper","InventoryGroupsHelpDefinition","InventoryTree","CredentialsHelper","TimerService","StreamListDefinition","HomeGroupListDefinition","HomeHostListDefinition","ActivityDetailDefinition"]).config(["$routeProvider",function(a){a.when("/jobs",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsListCtrl"}).when("/jobs/:id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobsEdit"}).when("/jobs/:id/job_events",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsList"}).when("/jobs/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/jobs/:job_id/job_events/:event_id",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobEventsEdit"}).when("/job_templates",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesList"}).when("/job_templates/add",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesAdd"}).when("/job_templates/:id",{templateUrl:urlPrefix+"partials/job_templates.html",controller:"JobTemplatesEdit"}).when("/projects",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsList"}).when("/projects/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsAdd"}).when("/projects/:id",{templateUrl:urlPrefix+"partials/projects.html",controller:"ProjectsEdit"}).when("/projects/:project_id/organizations",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsList"}).when("/projects/:project_id/organizations/add",{templateUrl:urlPrefix+"partials/projects.html",controller:"OrganizationsAdd"}).when("/hosts/:id/job_host_summaries",{templateUrl:urlPrefix+"partials/jobs.html",controller:"JobHostSummaryList"}).when("/inventories",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesList"}).when("/inventories/add",{templateUrl:urlPrefix+"partials/inventories.html",controller:"InventoriesAdd"}).when("/inventories/:inventory_id",{templateUrl:urlPrefix+"partials/inventory-edit.html",controller:"InventoriesEdit"}).when("/organizations",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsList"}).when("/organizations/add",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsAdd"}).when("/organizations/:organization_id",{templateUrl:urlPrefix+"partials/organizations.html",controller:"OrganizationsEdit"}).when("/organizations/:organization_id/admins",{templateUrl:urlPrefix+"partials/organizations.html",controller:"AdminsList"}).when("/organizations/:organization_id/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/organizations/:organization_id/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/organizations/:organization_id/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/teams",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsList"}).when("/teams/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsAdd"}).when("/teams/:team_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"TeamsEdit"}).when("/teams/:team_id/permissions/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsAdd"}).when("/teams/:team_id/permissions",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsList"}).when("/teams/:team_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"PermissionsEdit"}).when("/teams/:team_id/users",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersList"}).when("/teams/:team_id/users/:user_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"UsersEdit"}).when("/teams/:team_id/projects",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsList"}).when("/teams/:team_id/projects/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsAdd"}).when("/teams/:team_id/projects/:project_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"ProjectsEdit"}).when("/teams/:team_id/credentials",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsList"}).when("/teams/:team_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:team_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/credentials",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsList"}).when("/credentials/add",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsAdd"}).when("/credentials/:credential_id",{templateUrl:urlPrefix+"partials/credentials.html",controller:"CredentialsEdit"}).when("/users",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersList"}).when("/users/add",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersAdd"}).when("/users/:user_id",{templateUrl:urlPrefix+"partials/users.html",controller:"UsersEdit"}).when("/users/:user_id/credentials",{templateUrl:urlPrefix+"partials/users.html",controller:"CredentialsList"}).when("/users/:user_id/permissions/add",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsAdd"}).when("/users/:user_id/permissions",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsList"}).when("/users/:user_id/permissions/:permission_id",{templateUrl:urlPrefix+"partials/users.html",controller:"PermissionsEdit"}).when("/users/:user_id/credentials/add",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsAdd"}).when("/teams/:user_id/credentials/:credential_id",{templateUrl:urlPrefix+"partials/teams.html",controller:"CredentialsEdit"}).when("/login",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/logout",{templateUrl:urlPrefix+"partials/home.html",controller:"Authenticate"}).when("/home",{templateUrl:urlPrefix+"partials/home.html",controller:"Home"}).when("/home/groups",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeGroups"}).when("/home/hosts",{templateUrl:urlPrefix+"partials/subhome.html",controller:"HomeHosts"}).otherwise({redirectTo:"/home"})}]).run(["$cookieStore","$rootScope","CheckLicense","$location","Authorization","LoadBasePaths","ViewLicense","Timer","ClearScope","HideStream",function(a,b,c,d,e,f,g,h,i,j){f(),b.breadcrumbs=[],b.crumbCache=[],b.sessionTimer=h.init(),b.$on("$routeChangeStart",function(f,g){$("#stream-container").is(":visible")&&j(),/^\/(login|logout)/.test(d.path())||(b.lastPath=d.path(),a.put("lastPath",d.path())),e.isUserLoggedIn()===!1?g.templateUrl!==urlPrefix+"partials/login.html"&&d.path("/login"):b.sessionTimer.isExpired()?g.templateUrl!==urlPrefix+"partials/login.html"&&(b.sessionTimer.expireSession(),d.path("/login")):((void 0===b.current_user||null===b.current_user)&&e.restoreUserInfo(),c());var h=d.path().replace(/^\//,"").split("/")[0];""===h?h="home":h.replace(/\_/g," "),$('.nav-tabs a[href="#'+h+'"]').tab("show")}),e.getToken()?b.user_is_superuser=e.getUserInfo("is_superuser"):(b.sessionExpired=!1,a.put("sessionExpired",!1),d.path("/login"));var k=d.path().replace(/^\//,"").split("/")[0];""===k?(k="home",d.path("/home")):k.replace(/\_/g," "),$('.nav-tabs a[href="#'+k+'"]').tab("show"),b.viewCurrentUser=function(){d.path("/users/"+b.current_user.id)},b.viewLicense=function(){g()}}]);var $AnsibleConfig={tooltip_delay:{show:500,hide:100},debug_mode:!0,password_strength:45,session_timeout:1800};AdminsList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","AdminList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","GetBasePath","SelectionInit"],Authenticate.$inject=["$cookieStore","$window","$scope","$rootScope","$location","Authorization","ToggleClass","Alert","Wait","Timer","Empty"],CredentialsList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","CredentialList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","SelectionInit","GetChoices","Wait","Stream"],CredentialsAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","CredentialForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","GenerateList","SearchInit","PaginateInit","LookUpInit","UserList","TeamList","GetBasePath","GetChoices","Empty","KindChange","OwnerChange","FormSave"],CredentialsEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","CredentialForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","RelatedSearchInit","RelatedPaginateInit","ReturnToCaller","ClearScope","Prompt","GetBasePath","GetChoices","KindChange","UserList","TeamList","LookUpInit","Empty","OwnerChange","FormSave","Stream","Wait"],Home.$inject=["$scope","$compile","$routeParams","$rootScope","$location","Wait","ObjectCount","JobStatus","InventorySyncStatus","SCMSyncStatus","ClearScope","Stream","Rest","GetBasePath","ProcessErrors","Button"],HomeGroups.$inject=["$location","$routeParams","HomeGroupList","GenerateList","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","GetBasePath","SearchInit","PaginateInit","FormatDate","GetHostsStatusMsg","GetSyncStatusMsg","ViewUpdateStatus","Stream","GroupsEdit","Wait","Alert","Rest","Empty","InventoryUpdate","Find"],HomeHosts.$inject=["$location","$routeParams","HomeHostList","GenerateList","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","GetBasePath","SearchInit","PaginateInit","FormatDate","SetStatus","ToggleHostEnabled","HostsEdit","Stream","Find","ShowJobSummary"],InventoriesList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","InventoryList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","Wait","Stream","EditInventoryProperties"],InventoriesAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","InventoryForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","GenerateList","OrganizationList","SearchInit","PaginateInit","LookUpInit","GetBasePath","ParseTypeChange","Wait"],InventoriesEdit.$inject=["$scope","$location","$routeParams","$compile","GenerateList","ClearScope","InventoryGroups","InventoryHosts","BuildTree","Wait","GetSyncStatusMsg","InjectHosts","HostsReload","GroupsAdd","GroupsEdit","GroupsDelete","Breadcrumbs","LoadBreadCrumbs","Empty","Rest","ProcessErrors","InventoryUpdate","Alert","ToggleChildren","ViewUpdateStatus","GroupsCancelUpdate","Find","HostsCreate","EditInventoryProperties","HostsEdit","HostsDelete","ToggleHostEnabled","CopyMoveGroup","CopyMoveHost","Stream","GetBasePath","ShowJobSummary","ApplyEllipsis","WatchInventoryWindowResize","HelpDialog","InventoryGroupsHelp","Store"],JobEventsList.$inject=["$filter","$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","JobEventList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","LookUpInit","ToggleChildren","FormatDate","EventView","Refresh","Wait"],JobEventsEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","JobEventsForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ClearScope","GetBasePath","FormatDate","EventView","Wait"],JobHostSummaryList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","JobHostList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","Refresh","JobStatusToolTip","Wait"],JobTemplatesList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","JobTemplateList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","PromptPasswords","JobTemplateForm","CredentialList","LookUpInit","SubmitJob","Wait","Stream"],JobTemplatesAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","JobTemplateForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","GetBasePath","InventoryList","CredentialList","ProjectList","LookUpInit","md5Setup","ParseTypeChange","Wait","Empty"],JobTemplatesEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","JobTemplateForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","RelatedSearchInit","RelatedPaginateInit","ReturnToCaller","ClearScope","InventoryList","CredentialList","ProjectList","LookUpInit","PromptPasswords","GetBasePath","md5Setup","ParseTypeChange","JobStatusToolTip","FormatDate","Wait","Stream","Empty","Prompt"],JobsListCtrl.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","JobList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","LookUpInit","SubmitJob","FormatDate","Refresh","JobStatusToolTip","Empty","Wait"],JobsEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","JobForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","RelatedSearchInit","RelatedPaginateInit","ReturnToCaller","ClearScope","InventoryList","CredentialList","ProjectList","LookUpInit","PromptPasswords","GetBasePath","md5Setup","FormatDate","JobStatusToolTip","Wait"],OrganizationsList.$inject=["$routeParams","$scope","$rootScope","$location","$log","Rest","Alert","LoadBreadCrumbs","Prompt","GenerateList","OrganizationList","SearchInit","PaginateInit","ClearScope","ProcessErrors","GetBasePath","SelectionInit","Wait","Stream"],OrganizationsAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","OrganizationForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ClearScope","GetBasePath","ReturnToCaller","Wait"],OrganizationsEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","OrganizationForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","RelatedSearchInit","RelatedPaginateInit","Prompt","ClearScope","GetBasePath","Wait","Stream"],PermissionsList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","PermissionList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","CheckAccess","Wait"],PermissionsAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","PermissionsForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ClearScope","GetBasePath","ReturnToCaller","InventoryList","ProjectList","LookUpInit","CheckAccess","Wait","PermissionCategoryChange"],PermissionsEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","PermissionsForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","Prompt","GetBasePath","InventoryList","ProjectList","LookUpInit","CheckAccess","Wait","PermissionCategoryChange"],ProjectsList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","ProjectList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","SelectionInit","ProjectUpdate","ProjectStatus","FormatDate","Refresh","Wait","Stream","GetChoices","Empty"],ProjectsAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","ProjectsForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ClearScope","GetBasePath","ReturnToCaller","GetProjectPath","LookUpInit","OrganizationList","CredentialList","GetChoices","DebugForm","Wait"],ProjectsEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","ProjectsForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","RelatedSearchInit","RelatedPaginateInit","Prompt","ClearScope","GetBasePath","ReturnToCaller","GetProjectPath","Authorization","CredentialList","LookUpInit","GetChoices","Empty","DebugForm","Wait","Stream"],TeamsList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","TeamList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","SetTeamListeners","GetBasePath","SelectionInit","Wait","Stream"],TeamsAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","TeamForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","GenerateList","OrganizationList","SearchInit","PaginateInit","GetBasePath","LookUpInit","Wait"],TeamsEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","TeamForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","RelatedSearchInit","RelatedPaginateInit","ReturnToCaller","ClearScope","LookUpInit","Prompt","GetBasePath","CheckAccess","OrganizationList","Wait","Stream"],UsersList.$inject=["$scope","$rootScope","$location","$log","$routeParams","Rest","Alert","UserList","GenerateList","LoadBreadCrumbs","Prompt","SearchInit","PaginateInit","ReturnToCaller","ClearScope","ProcessErrors","GetBasePath","SelectionInit","Wait","Stream"],UsersAdd.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","UserForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","ReturnToCaller","ClearScope","GetBasePath","LookUpInit","OrganizationList","ResetForm","Wait"],UsersEdit.$inject=["$scope","$rootScope","$compile","$location","$log","$routeParams","UserForm","GenerateForm","Rest","Alert","ProcessErrors","LoadBreadCrumbs","RelatedSearchInit","RelatedPaginateInit","ReturnToCaller","ClearScope","GetBasePath","Prompt","CheckAccess","ResetForm","Wait","Stream"],angular.module("ActivityDetailDefinition",[]).value("ActivityDetailForm",{name:"activity",editTitle:"Activity Detail",well:!1,"class":"horizontal-narrow",formFieldSize:"col-lg-10",formLabelSize:"col-lg-2",fields:{user:{label:"Initiated by",type:"text",readonly:!0},operation:{label:"Action",type:"text",readonly:!0},changes:{label:"Changes",type:"textarea",ngHide:"!changes || changes =='' || changes == 'null'",readonly:!0}}}),angular.module("CredentialFormDefinition",[]).value("CredentialForm",{addTitle:"Create Credential",editTitle:"{{ name }}",name:"credential",well:!0,forceListeners:!0,actions:{stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"edit"}},fields:{name:{label:"Name",type:"text",addRequired:!0,editRequired:!0,autocomplete:!1},description:{label:"Description",type:"text",addRequired:!1,editRequired:!1},owner:{label:"Does this credential belong to a team or user?",type:"radio_group",ngChange:"ownerChange()",options:[{label:"User",value:"user",selected:!0},{label:"Team",value:"team"}],awPopOver:"
A credential must be associated with either a user or a team. Choosing a user allows only the selected user access to the credential. Choosing a team shares the credential with all team members.
",dataTitle:"Owner",dataPlacement:"right",dataContainer:"body"},user:{label:"User that owns this credential",type:"lookup",sourceModel:"user",sourceField:"username",ngClick:"lookUpUser()",ngShow:"owner == 'user'",awRequiredWhen:{variable:"user_required",init:"false"}},team:{label:"Team that owns this credential",type:"lookup",sourceModel:"team",sourceField:"name",ngClick:"lookUpTeam()",ngShow:"owner == 'team'",awRequiredWhen:{variable:"team_required",init:"false"}},kind:{label:"Type",excludeModal:!0,type:"select",ngOptions:"kind.label for kind in credential_kind_options",ngChange:"kindChange()",addRequired:!0,editRequired:!0,helpCollapse:[{hdr:"Select a Credential Type",content:"
\n
AWS
\n
Access keys for Amazon Web Services used for inventory management or deployment.
\n
Machine
\n
Authentication for remote machine access. This can include SSH keys, usernames, passwords, and sudo information. Machine credentials are used when submitting jobs to run playbooks against remote hosts.
Rackspace
\n
Access information for Rackspace Cloud used for inventory management or deployment.
\n
SCM
\n
Used to check out and synchronize playbook repositories with a remote source control management system such as Git, Subversion (svn), or Mercurial (hg). These credentials are used on the Projects tab.
Click on the regions field to see a list of regions for your cloud provider. You can select multiple regions, or choose All to include all regions. Tower will only be updated with Hosts associated with the selected regions.
Override variables found in ec2.ini and used by the inventory update script. For a detailed description of these variables view ec2.ini in the Ansible github repo.
Enter variables using either JSON or YAML syntax. Use the radio button to toggle between the two.
If checked, all variables for child groups and hosts will be removed and replaced by those found on the external source.
When not checked a merge will be performed, combining local variables with those found on the external source.
",dataTitle:"Overwrite Variables",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"update_on_launch",label:"Update on Launch",type:"checkbox",ngShow:"source.value !== '' && source.value !== null",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this inventory, refresh the inventory from the selected source before executing job tasks.
",dataTitle:"Update on Launch",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{labelClass:"col-lg-3",controlClass:"col-lg-5",save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("HostGroupsFormDefinition",[]).value("HostGroupsForm",{editTitle:"Host Groups",name:"host",well:!1,formLabelSize:"col-lg-3",formFieldSize:"col-lg-9",fields:{groups:{label:"Groups",type:"select",multiple:!0,ngOptions:"group.name for group in inventory_groups",addRequired:!0,editRequired:!0,awPopOver:"
Provide a host name, ip address, or ip address:port. Examples include:
',dataTitle:"Inventory Variables",dataPlacement:"right",dataContainer:"body"}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("JobEventDataDefinition",[]).value("JobEventDataForm",{editTitle:"{{ id }} - {{ event_display }}",name:"job_events",well:!1,"class":"horizontal-narrow",fields:{event_data:{label:!1,type:"textarea",readonly:!0,rows:18,"class":"modal-input-xxlarge"}}}),angular.module("JobEventsFormDefinition",[]).value("JobEventsForm",{name:"job_events",well:!1,forceListeners:!0,fields:{status:{labelClass:"job-{{ status }}",type:"custom",section:"Event",control:'
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",awRequiredWhen:{variable:"playbookrequired",init:"true"},column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
The number of parallel or simultaneous processes to use while executing the playbook. 0 signifies the default value from the ansible configuration file.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
',dataTitle:"Limit",dataPlacement:"right",dataContainer:"body"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting the Tower server using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",addRequired:!0,editRequired:!0,column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
For more information and examples see the Selecting Targets section under Inventory and Patterns in the Ansible documentation.
',dataContainer:"body",dataTitle:"Limit",dataPlacement:"right"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting Tower using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
A project must have at least one organization. Pick one organization now to create the project, and then after the project is created you can add additional organizations.
Only super users and organization administrators are allowed to make changes to projects. Associating one or more organizations to a project determins which organizations admins have access to modify the project.",dataTitle:"Organization",dataContainer:"body",dataPlacement:"right"},scm_type:{label:"SCM Type",type:"select",ngOptions:"type.label for type in scm_type_options",ngChange:"scmChange()",addRequired:!0,editRequired:!0},missing_path_alert:{type:"alertblock","class":"alert-info",ngShow:"showMissingPlaybooksAlert && scm_type.value == ''",alertTxt:'
WARNING: There are no unassigned playbook directories in the base project path {{ base_dir }}. Either the projects directory is empty, or all of the contents are already assigned to other projects. New projects can be checked out from source control by changing the SCM type option rather than specifying checkout paths manually. To continue with manual setup, log into the Tower host and ensure content is present in a subdirectory under {{ base_dir }}. Run "chown -R awx" on the content directory to ensure Tower can read the playbooks.
',closeable:!1},base_dir:{label:"Project Base Path",type:"textarea",showonly:!0,ngShow:"scm_type.value == ''",awPopOver:"
Base path used for locating playbooks. Directories found inside this path will be listed in the playbook directory drop-down. Together the base path and selected playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
",dataTitle:"Project Base Path",dataContainer:"body",dataPlacement:"right"},local_path:{label:"Playbook Directory",type:"select",id:"local-path-select",ngOptions:"path.label for path in project_local_paths",awRequiredWhen:{variable:"pathRequired",init:!1},ngShow:"scm_type.value == '' && !showMissingPlaybooksAlert",awPopOver:"
Select from the list of directories found in the base path.Together the base path and the playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
Note: If using SSH protocol for GitHub or Bitbucket, enter in the SSH key only, do not enter a username (other than git). Additionally, GitHub and Bitbucket do not support password authentication when using SSH protocol. GIT read only protocol (git://) does not use username or password information.',show:"scm_type.value == 'git'"},{hdr:"SVN URLs",content:'
Note: Mercurial does not support password authentication for SSH. If applicable, add the username, password and key below. Do not put the username and key in the URL. If using Bitbucket and SSH, do not supply your Bitbucket username.',show:"scm_type.value == 'hg'"}]},scm_branch:{labelBind:"scmBranchLabel",type:"text",ngShow:"scm_type && scm_type.value !== ''",addRequired:!1,editRequired:!1},credential:{label:"SCM Credential",type:"lookup",ngShow:"scm_type && scm_type.value !== ''",sourceModel:"credential",sourceField:"name",ngClick:"lookUpCredential()",addRequired:!1,editRequired:!1},checkbox_group:{label:"SCM Update Options",type:"checkbox_group",ngShow:"scm_type && scm_type.value !== ''",fields:[{name:"scm_clean",label:"Clean",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Remove any local modifications prior to performing an update.
",dataTitle:"SCM Clean",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_delete_on_update",label:"Delete on Update",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Delete the local repository in its entirety prior to performing an update.
Depending on the size of the repository this may significantly increase the amount of time required to complete an update.
",dataTitle:"SCM Delete",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_update_on_launch",label:"Update on Launch",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this project, perform an update to the local repository prior to starting the job.
",dataTitle:"SCM Update",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{add:{ngClick:"add('organizations')",icon:"icon-plus",label:"Add",awToolTip:"Add an organization"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('organizations', organization.id, organization.name)",icon:"icon-edit",awToolTip:"Edit the organization","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('organizations', organization.id, organization.name, 'organizations')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the organization"}}}}}),angular.module("TeamFormDefinition",[]).value("TeamForm",{addTitle:"Create Team",editTitle:"{{ name }}",name:"team",well:!0,collapse:!0,collapseTitle:"Team Settings",collapseMode:"edit",collapseOpen:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{name:{label:"Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!1},description:{label:"Description",type:"text",addRequired:!1,editRequired:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",awRequiredWhen:{variable:"teamrequired",init:"true"}}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",add:"Add a new credential"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Modify the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{add:{ngClick:"add('projects')",icon:"icon-plus",label:"Add"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('projects', project.id, project.name)",icon:"icon-edit",awToolTip:"Modify the project","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('projects', project.id, project.name, 'projects')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the project"}}},users:{type:"collection",title:"Users",iterator:"user",open:!1,actions:{add:{ngClick:"add('users')",icon:"icon-plus",label:"Add",awToolTip:"Add a user"}},fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('users', user.id, user.username)",icon:"icon-edit",awToolTip:"Edit user","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('users', user.id, user.username, 'users')",icon:"icon-terash","class":"btn-danger",awToolTip:"Remove user"}}}}}),angular.module("UserFormDefinition",[]).value("UserForm",{addTitle:"Create User",editTitle:"{{ username }}",name:"user",well:!0,forceListeners:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{first_name:{label:"First Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},last_name:{label:"Last Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},email:{label:"Email",type:"email",addRequired:!0,editRequired:!0,autocomplete:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",excludeMode:"edit",awRequiredWhen:{variable:"orgrequired",init:!0}},username:{label:"Username",type:"text",awRequiredWhen:{variable:"not_ldap_user",init:!0},autocomplete:!1},password:{label:"Password",type:"password",ngShow:"ldap_user == false",addRequired:!0,editRequired:!1,ngChange:"clearPWConfirm('password_confirm')",autocomplete:!1,chkPass:!0},password_confirm:{label:"Confirm Password",type:"password",ngShow:"ldap_user == false",addRequired:!1,editRequired:!1,awPassMatch:!0,associated:"password",autocomplete:!1},is_superuser:{label:"Superuser (User has full system administration privileges.)",type:"checkbox",trueValue:"true",falseValue:"false","default":"false",ngShow:"current_user['is_superuser'] == true"},ldap_user:{label:"Created by LDAP",type:"checkbox",readonly:!0}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",awToolTip:"Add a credential for this user"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Edit the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},admin_of_organizations:{type:"collection",title:"Admin of Organizations",iterator:"adminof",open:!1,base:"/organizations",actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},teams:{type:"collection",title:"Teams",iterator:"team",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}}}}),angular.module("InventoryGroupsHelpDefinition",[]).value("InventoryGroupsHelp",{story:{hdr:"Building your inventory",width:510,height:560,steps:[{intro:"Start by creating a group:",img:{src:"groups001.png",maxWidth:338,maxHeight:222},box:'Click on the groups list (the left side of the page) to add a new group.',autoOffNotice:!0},{intro:"Enter group properties:",img:{src:"groups002.png",maxWidth:443,maxHeight:251},box:'Enter the group name, a description and any inventory variables. Variables can be entered using either JSON or YAML syntax. For more on inventory variables, see docs.ansible.com/intro_inventory.html'},{intro:"Cloud inventory: select cloud source",img:{src:"groups003.png",maxWidth:412,maxHeight:215},box:'For a cloud inventory, choose the cloud provider from the list and select your credentials. If you have not already setup credentials for the provider, you will need to do that first on the Credentials tab.'},{intro:"Cloud inventory: synchronize Tower with the cloud",img:{src:"groups004.png",maxWidth:261,maxHeight:221},box:'To pull the cloud inventory into Tower, initiate an inventory sync by clicking .'},{intro:"Groups can have subgroups:",img:{src:"groups005.png",maxWidth:430,maxHeight:206},box:'
First, select a group. Then click to create a new group. The new group will be added to the selected group.
'},{intro:"Copy or move groups:",img:{src:"groups006.png",maxWidth:263,maxHeight:211},box:'
Copy or move a group by dragging and dropping its name onto another group name. A dialog will appear asking if the group should be coppied or moved.
Your Ansible Tower license has reached capacity for the number of managed hosts allowed. You will not be able to add any additional hosts.
"+i,c(d,f,g,null,!0)))}}]),angular.module("ChildrenHelper",["RestServices","Utilities"]).factory("ToggleChildren",[function(){return function(a){function b(a){var b;for(i[a].ngicon="fa fa-minus-square-o node-toggle",b=a+1;b10?10:i,i=3>i?3:i,f.fields[h].rows=i);break;case"results":if(a.event_data&&a.event_data.res&&void 0===a.event_data.res[h])delete f.fields[h];else if(Array.isArray(a.event_data.res[h])&&0!==a.event_data.res[h].length){for(j="",c=0;c10?10:i,i=3>i?3:i,f.fields[h].rows=i)}else delete f.fields[h];break;case"module_name":case"module_args":a.event_data&&a.event_data.res&&(void 0===a.event_data.res.invocation||void 0===a.event_data.res.invocation[h])&&delete f.fields[h]}b=d.inject(f,{mode:"edit",modal:!0,related:!1}),d.reset(),b.formModalAction=function(){$("#form-modal").modal("hide")},b.formModalActionLabel="OK",b.formModalCancelShow=!1,b.formModalInfo="View JSON",$("#form-modal .btn-success").removeClass("btn-success").addClass("btn-none"),$("#form-modal").addClass("skinny-modal"),b.formModalHeader=a.event_display.replace(/^\u00a0*/g,""),b.formModalInfoAction=function(){var b=g,c=b.inject(l,{mode:"edit",modal:!0,related:!1,modal_selector:"#form-modal2",modal_body_id:"form-modal2-body",modal_title_id:"formModal2Header"});b.reset(),c.formModal2Header=a.event_display.replace(/^\u00a0*/g,""),c.event_data=JSON.stringify(a.event_data,null," "),c.formModal2ActionLabel="OK",c.formModal2CancelShow=!1,c.formModal2Info=!1,c.formModalInfo="View JSON",c.formModal2Action=function(){$("#form-modal2").modal("hide")},$("#form-modal2 .btn-success").removeClass("btn-success").addClass("btn-none")},"string"==typeof a.event_data.res&&(b.traceback=a.event_data.res);for(h in f.fields)switch(h){case"status":b.status=a.failed?"error":a.changed?"changed":"success";break;case"created":n=new Date(a.created),b.created=k(n);break;case"host":a.summary_fields&&a.summary_fields.host&&(b.host=a.summary_fields.host.name);break;case"id":case"task":case"play":b[h]=a[h];break;case"start":case"end":a.event_data&&a.event_data.res&&!m(a.event_data.res[h])&&(b[h]=a.event_data.res[h]);break;case"results":if(Array.isArray(a.event_data.res[h])&&a.event_data.res[h].length>0){for(j="",c=0;c button.',"alert-info"):(f("start"),a.setUrl(l.related.inventory_source),a.get().success(function(a){var b=a.related.current_update?a.related.current_update:a.related.last_update;d({group_name:a.summary_fields.group.name,last_update:b,license_error:a.summary_fields.last_update&&a.summary_fields.last_update.license_error?!0:!1,tree_id:j,group_id:k,parent_scope:i})}).error(function(a,c){f("stop"),b(i,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+l.related.inventory_source+" POST returned status: "+c})})))}}]).factory("GetHostsStatusMsg",[function(){return function(a){var b,c,d,e=a.active_failures,f=a.total_hosts;return e>0?(b=f+(1===f?" host":" hosts")+". "+e+" with failed jobs.",d="true",c=!0):(c=!1,0===f?(b="Group contains 0 hosts.",d="na"):(b=f+(1===f?" host":" hosts")+". No job failures",d="false")),{tooltip:b,failures:c,"class":d}}}]).factory("GetSyncStatusMsg",[function(){return function(a){var b,c,d,e=a.status,f="",g="Start sync process";switch(b=e,c="icon-cloud-"+b,e){case"never updated":b="never",c="icon-cloud-na disabled",d='Sync not performed. Click to start it now.';break;case"none":case"":f="btn-disabled",b="n/a",c="icon-cloud-na disabled",d='Cloud source not configured. Click to update.',g=d;break;case"failed":d="Sync failed. Click to view log.";break;case"successful":d="Sync completed. Click to view log.";break;case"updating":d="Sync running"}return{"class":c,tooltip:d,status:b,launch_class:f,launch_tip:g}}}]).factory("SourceChange",["GetBasePath","CredentialList","LookUpInit","Empty",function(a,b,c,d){return function(e){var f,g,h=e.scope,i=e.form;d(h.source)||("file"===h.source.value?h.sourcePathRequired=!0:(h.sourcePathRequired=!1,h.source_path="",h[i.name+"_form"].source_path.$setValidity("required",!0)),"rax"===h.source.value?(h.source_region_choices=h.rax_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])):"ec2"===h.source.value&&(h.source_region_choices=h.ec2_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])),("rax"===h.source.value||"ec2"===h.source.value)&&(f="rax"===h.source.value?"rax":"aws",g=a("credentials")+"?cloud=true&kind="+f,c({url:g,scope:h,form:i,list:b,field:"credential"})))}}]).factory("GroupsCancelUpdate",["Rest","ProcessErrors","Alert","Wait","Find",function(a,b,c,d,e){return function(f){var g,h=f.scope,i=f.tree_id;h.removeCancelUpdate&&h.removeCancelUpdate(),h.removeCancelUpdate=h.$on("CancelUpdate",function(e,f){a.setUrl(f),a.post().success(function(){d("stop"),c("Inventory Sync Cancelled",'Your request to cancel the sync process was submitted to the task manger. Click the button to monitor the status.',"alert-info")}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+f+" failed. POST status: "+c})})}),h.removeCheckCancel&&h.removeCheckCancel(),h.removeCheckCancel=h.$on("CheckCancel",function(e,f,g){var i=g?g:f;i+="cancel/",a.setUrl(i),a.get().success(function(a){a.can_cancel?h.$emit("CancelUpdate",i):(d("stop"),c("Cancel Inventory Sync",'Either you do not have access or the sync process completed. Click the button to view the latest status.',"alert-info"))}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+i+" failed. GET status: "+c})})}),g=e({list:h.groups,key:"id",val:i}),h.selected_tree_id=g.id,h.selected_group_id=g.group_id,!g||"updating"!==g.status&&"pending"!==g.status?c("Cancel Inventory Sync",'The sync process completed. Click the to view the latest status.',"alert-info"):(d("start"),a.setUrl(g.related.inventory_source),a.get().success(function(a){h.$emit("CheckCancel",a.related.last_update,a.related.current_update)}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+g.related.inventory_source+" failed. GET status: "+c})}))}}]).factory("GroupsAdd",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","ParseTypeChange","GroupsEdit","Wait","GetChoices","GetSourceTypeOptions","LookUpInit","BuildTree","SourceChange","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){return function(b){var c,d=b.inventory_id,i=void 0!==b.group_id?b.group_id:null,m=b.scope,q=null!==i?k("groups")+i+"/children/":k("inventory")+d+"/groups/",u=g,v=h,w=v.inject(u,{mode:"add",modal:!0,related:!1,show_modal:!1});$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),w.formModalActionLabel="Save",w.formModalCancelShow=!0,w.parseType="yaml",w.source=null,l(w),v.reset(),w.removeAddTreeRefreshed&&w.removeAddTreeRefreshed(),w.removeAddTreeRefreshed=w.$on("GroupTreeRefreshed",function(){a.formModalHeader=null,a.formModalCancleShow=null,a.formModalActionLabel=null,n("stop"),$("#form-modal").modal("hide"),w.removeAddTreeRefreshed()}),w.removeSaveComplete&&w.removeSaveComplete(),w.removeSaveComplete=w.$on("SaveComplete",function(a,b,c){c||(w.searchCleanup&&w.searchCleanup(),w.formModalActionDisabled=!1,r({scope:m,inventory_id:d,refresh:!0,new_group_id:b}),t())}),w.removeFormSaveSuccess&&w.removeFormSaveSuccess(),w.removeFormSaveSuccess=w.$on("formSaveSuccess",function(a,b,c){var d,g,h,i,k=!1,l={};if(null!==w.source.value&&""!==w.source.value){for(l.group=b,l.source=w.source.value,l.source_path=w.source_path,l.credential=w.credential,l.overwrite=w.overwrite,l.overwrite_vars=w.overwrite_vars,l.update_on_launch=w.update_on_launch,d=$("#s2id_group_source_regions").select2("data"),g=[],h=0;h"+A.summary_fields.group.name+". Use the Refresh button to monitor the status.","alert-info"):o({scope:A,group_id:d,url:A.group_update_url,group_name:A.name,group_source:A.source.value})},A.sourceChange=function(){v({scope:A,form:g})}}}]).factory("GroupsDelete",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","Wait","BuildTree","Find",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){return function(a){var b,c=a.scope,d=a.tree_id,f=a.inventory_id,g=n({list:c.groups,key:"id",val:d}),h=k("inventory")+f+"/groups/";b=function(){$("#prompt-modal").on("hidden.bs.modal",function(){l("start")}),$("#prompt-modal").modal("hide"),e.setUrl(h),e.post({id:g.group_id,disassociate:1}).success(function(){$("#prompt-modal").off(),c.$emit("GroupDeleteCompleted")}).error(function(a,b){l("stop"),j(c,a,b,null,{hdr:"Error!",msg:"Call to "+h+" failed. POST returned status: "+b})})},i({hdr:"Delete Group",body:"
Are you sure you want to delete group "+g.name+"?
",action:b,"class":"btn-danger"})}}]).factory("ShowUpdateStatus",["$rootScope","$location","$log","$routeParams","Rest","Alert","GenerateForm","Prompt","ProcessErrors","GetBasePath","FormatDate","InventoryStatusForm","Wait","Empty","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){return function(a){function b(a){var b,d;return b=a.match(/\n/g),d=b?b.length:1,d>c?c:d}var c,d,h,j,n,p,q,r=a.group_name,s=a.last_update,t=g,u=l,v=a.license_error;void 0===s||null===s||""===s?(m("stop"),f("Missing Configuration","The selected group is not configured for inventory sync. Edit the group and provide Source information.","alert-info")):(d='
\n
\n',$("#inventory-modal-container").empty().append(d),h=t.inject(u,{mode:"edit",id:"form-container",breadCrumbs:!1,related:!1}),j=$(document).width(),n=$("body").height(),j>1199?(p=675,q=750>n?n-20:750,c=18):1199>=j&&j>=768?(p=550,q=620>n?n-15:620,c=12):(p=j-20,q=500>n?n:500,c=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:p,height:q,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#inventory-modal-container").empty(),o()},open:function(){m("stop")}}),e.setUrl(s),e.get().success(function(a){for(var c in u.fields)a[c]&&(h[c]="created"===c?k(new Date(a[c])):a[c]);h.license_error=v,h.status_rows=b(a.status),h.stdout_rows=b(a.result_stdout),h.traceback_rows=b(a.result_traceback),$("#status-modal-dialog").dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(h,a,b,null,{hdr:"Error!",msg:"Failed to retrieve last update: "+s+". GET status: "+b})}))}}]),angular.module("HostsHelper",["RestServices","Utilities","ListGenerator","HostListDefinition","SearchHelper","PaginationHelpers","ListGenerator","AuthService","HostsHelper","InventoryHelper","RelatedSearchHelper","InventoryFormDefinition","SelectionHelper","HostGroupsFormDefinition"]).factory("SetEnabledMsg",[function(){return function(a){a.enabledToolTip=a.has_inventory_sources?a.enabled?"Host is available":"Host is not available":a.enabled?"Host is available. Click to toggle.":"Host is not available. Click to toggle."}}]).factory("SetHostStatus",["SetEnabledMsg",function(a){return function(b){b.activeFailuresLink="/#/hosts/"+b.id+"/job_host_summaries/?inventory="+b.inventory+"&host_name="+encodeURI(b.name),b.has_active_failures===!0?(b.badgeToolTip="Most recent job failed. Click to view jobs.",b.active_failures="failed"):b.has_active_failures===!1&&null===b.last_job?(b.has_active_failures="none",b.badgeToolTip="No job data available.",b.active_failures="n/a"):b.has_active_failures===!1&&null!==b.last_job&&(b.badgeToolTip="Most recent job successful. Click to view jobs.",b.active_failures="success"),b.enabled_flag=b.enabled,a(b)}}]).factory("SetStatus",["SetEnabledMsg","Empty",function(a,b){return function(c){function d(a){return a.length>25?a.substr(0,25)+"...":a}function e(a){var b,c,e;if(a.has_active_failures===!0||a.has_active_failures===!1&&null!==a.last_job)if(a.has_active_failures===!0?(a.badgeToolTip="Most recent job failed. Click to view jobs.",a.active_failures="failed"):(a.badgeToolTip="Most recent job successful. Click to view jobs.",a.active_failures="success"),a.summary_fields.recent_jobs.length>0){for(e=a.summary_fields.recent_jobs.sort(function(a,b){return-1*(a-b)}),h="Recent Jobs",g='
";else a.has_active_failures===!1&&null===a.last_job&&(a.has_active_failures="none",a.badgeToolTip="No job data available.",a.active_failures="n/a");a.job_status_html=g,a.job_status_title=h}var f,g,h,i=c.scope,j=c.host;if(b(j))for(f=0;fAre you sure you want to delete host "+j+" from group "+n.name+"?
\n",d=j("hosts")+l+"/",f=o.inject(null,{mode:"edit",modal:!0,related:!1,html:c}),b=0;bGroups',f.formModalCancelShow=!0,f.formModalActionDisabled=!0,$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),f.hostGroupChangeRemove&&f.hostGroupChangeRemove(),f.hostGroupChangeRemove=f.$on("hostGroupChange",function(){p.pop(),0===p.length&&(h=function(){setTimeout(function(){m("stop")},500)},k({scope:f,inventory_id:n,group_id:f.group_id,action:h}))}),f.formModalAction=function(){var a,b,c;for($("#form-modal").modal("hide"),m("start"),a=0;a0?(f.assignedGroups=null,f.leftButtonDisabled=!0,f.rightButtonDisabled=!1):f.rightButtonDisabled=!0},f.rightChange=function(){null!==f.assignedGroups&&f.assignedGroups.length>0?(f.selectedGroups=null,f.leftButtonDisabled=!1,f.rightButtonDisabled=!0):f.leftButtonDisabled=!0},f.moveLeft=function(){var a,b,c,d;for(a=0;af.available_groups[b].name.toLowerCase()&&f.assignedGroups[a].name.toLowerCase()f.host_groups[b].name.toLowerCase()&&f.selectedGroups[a].name.toLowerCase()0){for(j("stop"),u+='\n",m=angular.element(document.getElementById("password-body")),m.html(u),c(m.contents())(q),$("#password-modal").modal(),$("#password-modal").on("shown.bs.modal",function(){$("#password-body").find('input[type="password"]:first').focus()})}else q.startJob()}}]).factory("SubmitJob",["PromptPasswords","$compile","Rest","$location","GetBasePath","CredentialList","LookUpInit","CredentialForm","ProcessErrors","JobTemplateForm","Wait",function(a,b,c,d,e,f,g,h,i,j,k){return function(b){function l(b){var e,f,g;m.credentialWatchRemove&&m.credentialWatchRemove(),e=(new Date).toISOString(),f=b.related.jobs?b.related.jobs:b.related.job_template+"jobs/",g=o?o:b.name,k("start"),c.setUrl(f),c.post({name:g+" "+e,description:b.description,job_template:b.id,inventory:b.inventory,project:b.project,playbook:b.playbook,credential:b.credential,forks:b.forks,limit:b.limit,verbosity:b.verbosity,extra_vars:b.extra_vars}).success(function(b){m.job_id=b.id,b.passwords_needed_to_start.length>0?a({scope:m,passwords:b.passwords_needed_to_start,start_url:b.related.start,form:h}):(c.setUrl(b.related.start),c.post().success(function(){k("stop");var a=d.path().replace(/^\//,"").split("/")[0];"jobs"===a?m.refresh():d.path("/jobs")}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to start job. POST returned status: "+b})}))}).error(function(a,b){k("stop"),i(m,a,b,null,{hdr:"Error!",msg:"Failed to create job. POST returned status: "+b})})}var m=b.scope,n=b.id,o=b.template?b.template:null,p=d.path().replace(/^\//,"").split("/")[0],q=e(p)+n+"/";k("start"),c.setUrl(q),c.get().success(function(a){m.credential="",""===a.credential||null===a.credential?(k("stop"),m.credentialWatchRemove&&m.credentialWatchRemove(),m.credentialWatchRemove=m.$watch("credential",function(b,c){b!==c&&""!==m.credential&&null!==m.credential&&void 0!==m.credential&&(a.credential=m.credential,l(a))}),g({scope:m,form:j,current_item:null,list:f,field:"credential",hdr:"Credential Required"}),m.lookUpCredential()):l(a)}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to get job template details. GET returned status: "+b})})}}]).factory("ProjectUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","ProjectsForm","Wait",function(a,b,c,d,e,f,g,h,i){return function(b){var d=b.scope,j=b.project_id,k=e("projects")+j+"/update/";d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(){i("stop"),g("Update Started","The request to start the SCM update process was submitted. To monitor the update status, refresh the page by clicking the Refresh button.","alert-info"),d.refresh()}),d.removeSCMSubmit&&d.removeSCMSubmit(),d.removeSCMSubmit=d.$on("SCMSubmit",function(b,c,e){a({scope:d,passwords:c,start_url:k,form:h,extra_html:e})}),i("start"),c.setUrl(k),c.get().success(function(a){var b,c;if(i("stop"),a.can_update){for(c="",b=0;b\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="\n",d.projects[b].scm_username&&(c+='
\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="
\n");break}c+="",d.$emit("SCMSubmit",a.passwords_needed_to_update,c)}else g("Permission Denied","You do not have access to update this project. Please contact your system administrator.","alert-danger")}).error(function(a,b){f(d,a,b,null,{hdr:"Error!",msg:"Failed to get project update details: "+k+" GET status: "+b})})}}]).factory("InventoryUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","GroupForm","BuildTree","Wait",function(a,b,c,d,e,f,g,h,i,j){return function(b){var d=b.scope,e=b.url,i=b.group_id,k=b.tree_id;d.removeHostReloadComplete&&d.removeHostReloadComplete(),d.removeHostReloadComplete=d.$on("HostReloadComplete",function(){j("stop"),g("Update Started",'Your request to start the inventory sync process was submitted. Monitor progress by clicking the button.',"alert-info"),d.removeHostReloadComplete&&d.removeHostReloadComplete()}),d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(a,b){"started"===b&&(d.refreshGroups?(d.selected_tree_id=k,d.selected_group_id=i,d.refreshGroups()):d.refresh&&d.refresh(),d.$emit("HostReloadComplete"))}),d.removeInventorySubmit&&d.removeInventorySubmit(),d.removeInventorySubmit=d.$on("InventorySubmit",function(b,c,f){a({scope:d,passwords:c,start_url:e,form:h,extra_html:f})}),j("start"),c.setUrl(e),c.get().success(function(a){a.can_update?d.$emit("InventorySubmit",a.passwords_needed_to_update):(j("stop"),g("Permission Denied","You do not have access to run the update. Please contact your system administrator.","alert-danger"))}).error(function(a,b){j("stop"),f(d,a,b,null,{hdr:"Error!",msg:"Failed to get inventory_source details. "+e+"GET status: "+b})})}}]),angular.module("JobsHelper",["Utilities","FormGenerator","JobSummaryDefinition","InventoryHelper"]).factory("JobStatusToolTip",[function(){return function(a){var b;switch(a){case"successful":case"success":b="There were no failed tasks.";break;case"failed":b="Some tasks encountered errors.";break;case"canceled":b="Stopped by user request.";break;case"new":b="In queue, waiting on task manager.";break;case"waiting":b="SCM Update or Inventory Update is executing.";break;case"pending":b="Not in queue, waiting on task manager.";break;case"running":b="Playbook tasks executing."}return b}}]).factory("ShowJobSummary",["Rest","Wait","GetBasePath","FormatDate","ProcessErrors","GenerateForm","JobSummary","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h){return function(i){function j(a){var b=a.match(/\n/g),c=b?b.length:1;return c>p?20:c}var k,l,m,n,o,p,q,r,s=i.job_id,t=f,u=g;r='
Only allow the user or team to view the inventory.
\n
Write
\n
Allow the user or team to modify hosts and groups contained in the inventory, add new hosts and groups, and perform inventory sync operations.\n
Admin
\n
Allow the user or team full access to the inventory. This includes reading, writing, deletion of the inventory and inventory sync operations.
\n
\n"):(b.projectrequired=!0,b.permissionTypeHelp="
\n
Run
\n
Allow the user or team to perform a live deployment of the project against the inventory. In Run mode modules will be executed, and changes to the inventory will occur.
\n
Check
\n
Only allow the user or team to deploy the project against the inventory as a dry-run operation. In Check mode, module operations will only be simulated. No changes will occur.
\n
\n"),c&&(b.permission_type="Inventory"===b.category?"read":"run")}}]),angular.module("ProjectPathHelper",["RestServices","Utilities"]).factory("GetProjectPath",["Alert","Rest","GetBasePath","ProcessErrors",function(a,b,c,d){return function(a){function e(a){var b,c,d=[],e=[];for(b=0;b\n',$("#projects-modal-container").empty().append(b),c=q.inject(r,{mode:"edit",id:"form-container",related:!1,breadCrumbs:!1}),q.reset(),d=$(document).width(),f=$("body").height(),d>1199?(h=675,j=750>f?f-20:750,n=20):1199>=d&&d>=768?(h=550,j=620>f?f-15:620,n=15):(h=d-20,j=500>f?f:500,n=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:h,height:j,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#projects-modal-container").empty()},open:function(){m("stop")}}),e.setUrl(p),e.get().success(function(a){var b,d=a;for(b in r.fields)d[b]?c[b]="created"===b?k(new Date(d[b])):d[b]:d.summary_fields.project[b]&&(c[b]=d.summary_fields.project[b]);$("#status-modal-dialog").dialog({title:d.summary_fields.project.name+" Status"}).dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(c,a,b,r,{hdr:"Error!",msg:"Failed to retrieve status of project: "+o+". GET status: "+b})})}}]),angular.module("SelectionHelper",["Utilities","RestServices"]).factory("SelectionInit",["Rest","Alert","ProcessErrors","ReturnToCaller","Wait",function(a,b,c,d,e){return function(b){var f,g=b.scope,h=b.list,i=b.url,j=b.returnToCaller;f=void 0!==b.selected?b.selected:[],g.formModalActionDisabled=!0,g.disableSelectBtn=!0,g["toggle_"+h.iterator]=function(a,b){var c,d,e;for(c=0;c0?(g.formModalActionDisabled=!1,g.disableSelectBtn=!1):(g.formModalActionDisabled=!0,g.disableSelectBtn=!0)},g.finishSelection=function(){function b(){f=[],void 0!==j?d(j):($("#form-modal").modal("hide"),g.$emit("modalClosed"))}function k(b){a.post(b).success(function(a,b){m.push({result:"success",data:a,status:b}),g.$emit("callFinished")}).error(function(a,b,c){m.push({result:"error",data:a,status:b,headers:c}),g.$emit("callFinished")})}a.setUrl(i);var l,m=[];if(g.formModalActionDisabled=!0,g.disableSelectBtn=!0,e("start"),g.callFinishedRemove&&g.callFinishedRemove(),g.callFinishedRemove=g.$on("callFinished",function(){var a,d=0;if(m.length===f.length){for(e("stop"),a=0;a0)for(l=0;lh)h++,setTimeout(1e3,e());else if("success"===g.status)return d(a)}var f,g={},h=0;return null===c.apiDefaults||void 0===c.apiDefaults?(f="/api/v1/",b.setUrl(f),b.get().success(function(a){var b,d=a;for(b in d)switch(b){case"organizations":d[b].iterator="organization";break;case"jobs":d[b].iterator="job";break;case"users":d[b].iterator="user";break;case"teams":d[b].iterator="team";break;case"hosts":d[b].iterator="host";break;case"groups":d[b].iterator="group";break;case"projects":d[b].iterator="project";break;case"inventories":d[b].iterator="inventory"}c.apiDefaults=d,g={status:"success"}}).error(function(a,b){g={status:"error",msg:"Call to "+f+" failed. GET returned status: "+b}}),e()):d(a)}}]),angular.module("InventoryHelper",["RestServices","Utilities","OrganizationListDefinition","ListGenerator","AuthService","InventoryHelper","InventoryFormDefinition","ParseHelper","SearchHelper"]).factory("WatchInventoryWindowResize",["ApplyEllipsis",function(a){return function(){var b;$(window).resize(function(){clearTimeout(b),b=setTimeout(function(){$("#groups_table .name-column").each(function(){var a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%";$(this).find(".group-name").css({width:e})}),a("#groups_table .group-name a"),a("#hosts_table .host-name a")},100)})}}]).factory("SaveInventory",["InventoryForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","Wait",function(a,b,c,d,e,f,g,h,i){return function(e){var f,h,j,k=e.scope,l=a,m=g("inventory");i("start");try{if(h="json"===k.inventoryParseType?JSON.parse(k.inventory_variables):jsyaml.load(k.inventory_variables),"object"!=typeof h)throw"failed to return an object!";j={};for(f in l.fields)"inventory_variables"!==f&&(l.fields[f].realName?j[l.fields[f].realName]=k[f]:j[f]=k[f]);b.setUrl(m+k.inventory_id+"/"),b.put(j).success(function(a){k.inventory_variables?(b.setUrl(a.related.variable_data),b.put(h).success(function(){i("stop"),k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory varaibles. PUT returned status: "+b})})):k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory. POST returned status: "+b})})}catch(n){i("stop"),c("Error","Error parsing inventory variables. Parser returned: "+n)}}}]).factory("EditInventoryProperties",["InventoryForm","GenerateForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","SaveInventory","Wait","Store","SearchInit",function(a,b,c,d,e,f,g,h,i,j,k,l,m){return function(n){var o,p=n.scope,q=n.inventory_id,r=b,s=a,t={},u=l("CurrentSearchParams");s.well=!1,o=r.inject(s,{mode:"edit",modal:!0,related:!1,modal_show:!1}),s.well=!0,i(o,"inventory_variables","inventoryParseType"),o.inventoryParseType="yaml",o.formModalActionLabel="Save",o.formModalCancelShow=!0,o.formModalInfo=!1,o.formModalHeader="Inventory Properties",k("start"),c.setUrl(h("inventory")+q+"/"),c.get().success(function(a){var b,c;for(b in s.fields){if("inventory_variables"===b){if($.isEmptyObject(a.variables)||"{}"===a.variables||"null"===a.variables||""===a.variables)o.inventory_variables="---";else try{c=JSON.parse(a.variables),o.inventory_variables=jsyaml.safeDump(c)}catch(e){d("Variable Parse Error","Attempted to parse variables for inventory: "+q+". Parse returned: "+e),console&&(console.log(e),console.log("data:"),console.log(a.variables)),o.inventory_variables="---"}t.inventory_variables=o.variables}else"inventory_name"===b?(o[b]=a.name,t[b]=o[b]):"inventory_description"===b?(o[b]=a.description,t[b]=o[b]):a[b]&&(o[b]=a[b],t[b]=o[b]);s.fields[b].sourceModel&&a.summary_fields&&a.summary_fields[s.fields[b].sourceModel]&&(o[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField],t[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField])}f({scope:o,form:s,current_item:o.organization,list:g,field:"organization"}),k("stop"),$("#form-modal").modal("show")}).error(function(a,b){e(o,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+q+". GET returned: "+b})}),o.removeInventorySaved&&o.removeInventorySaved(),o.removeInventorySaved=o.$on("InventorySaved",function(){$("#form-modal").modal("hide"),o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1}),p.$emit("RefreshInventories")}),o.cancelModal=function(){o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1})},o.formModalAction=function(){p.inventory_id=q,p.inventory_name=o.inventory_name,j({scope:o})}}}]),angular.module("md5Helper",["RestServices","Utilities"]).factory("md5Setup",[function(){return function(a){var b=a.scope,c=a.master,d=a.check_field,e=a.default_val;b[d]=e,c[d]=e,b.genMD5=function(a){var c=new Date;b[a]=$.md5("AnsibleWorks"+c.getTime())},b.toggleCallback=function(a){"false"===b.allow_callbacks&&(b[a]="")},b.selectAll=function(a){$('input[name="'+a+'"]').focus().select()}}}]),angular.module("RefreshRelatedHelper",["RestServices","Utilities","PaginationHelpers"]).factory("RefreshRelated",["ProcessErrors","Rest","Wait","PageRangeSetup",function(a,b,c,d){return function(e){var f=e.scope,g=e.set,h=e.iterator,i=e.url;b.setUrl(i),b.get().success(function(a){d({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[g]=a.results,f[h+"Loading"]=!1,f[h+"HoldInput"]=!1,c("stop"),f.$emit("related"+g)}).error(function(b,c){a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RefreshHelper",["RestServices","Utilities","PaginationHelpers"]).factory("Refresh",["ProcessErrors","Rest","Wait","Empty","PageRangeSetup",function(a,b,c,d,e){return function(d){var f=d.scope,g=d.set,h=d.iterator,i=d.url;f.current_url=i,b.setUrl(i),b.get().success(function(a){var b,d;for(e({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[h+"Loading"]=!1,b=1;3>=b;b++)d=1===b?"":b,f[h+"HoldInput"+d]=!1;f[g]=a.results,window.scrollTo(0,0),c("stop"),f.$emit("PostRefresh")}).error(function(b,c){f[h+"HoldInput"]=!1,a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RelatedSearchHelper",["RestServices","Utilities","RefreshRelatedHelper"]).factory("RelatedSearchInit",["$timeout","Alert","Rest","RefreshRelated","Wait",function(a,b,c,d,e){return function(a){function b(a){var b,c,d,e;for(e in h.related)if("tree"!==h.related[e].type&&(void 0===a||a===h.related[e].iterator)){b=h.related[e].iterator;for(d in h.related[e].fields)if(h.related[e].fields[d].key){f[b+"SearchField"]=d,f[b+"SearchFieldLabel"]=h.related[e].fields[d].label;break}f[b+"SortOrder"]=null,f[b+"SearchType"]="icontains",f[b+"SearchTypeLabel"]="Contains",f[b+"SearchValue"]=null,f[b+"SelectShow"]=!1,f[b+"ShowStartBtn"]=!0,f[b+"HideAllStartBtn"]=!1,c=f[b+"SearchField"],!h.related[e].fields[c].searchType||"boolean"!==h.related[e].fields[c].searchType&&"select"!==h.related[e].fields[c].searchType||(f[b+"SelectShow"]=!0,f[b+"SearchSelectOpts"]=h.fields[c].searchOptions),h.related[e].fields[c].searchType&&"gtzero"===h.related[e].fields[c].searchType&&(f[b+"InputHide"]=!0)}}var c,f=a.scope,g=a.relatedSets,h=a.form;b(),f.resetSearch=function(a){b(a),f.search(a)},f.setSearchField=function(a,b,c){var d,e;for(e in h.related)h.related[e].iterator===a&&(d=h.related[e].fields[b]);f[a+"SearchFieldLabel"]=c,f[a+"SearchField"]=b,f[a+"SearchValue"]="",f[a+"SelectShow"]=!1,f[a+"InputHide"]=!1,f[a+"ShowStartBtn"]=!0,void 0!==d.searchType&&"gtzero"===d.searchType&&(f[a+"InputHide"]=!0,f[a+"ShowStartBtn"]=!1),void 0===d.searchType||"boolean"!==d.searchType&&"select"!==d.searchType||(f[a+"SelectShow"]=!0,f[a+"SearchSelectOpts"]=d.searchOptions),void 0!==d.searchType&&"int"===d.searchType&&(f[a+"SearchType"]="int"),f.search(a)},f.setSearchType=function(a,b,c){f[a+"SearchTypeLabel"]=c,f[a+"SearchType"]=b,f.search(a)},f.startSearch=function(a,b){13===a.keyCode&&f.search(b)},f.search=function(a){e("start"),f[a+"Loading"]=!0,f[a+"HoldInput"]=!0,f[a+"SearchValue"]&&(f[a+"ShowStartBtn"]=!1),"host"===a&&"has_active_failures"===f.hostSearchField&&(f.hostFailureFilter=f.hostSearchSelectValue&&1===f.hostSearchSelectValue.value?!0:!1);var b,i,j,k,l;for(i in g)if(g[i].iterator===a){j=i,k=g[i].url;for(b in h.related[i].fields)h.related[i].fields[b].key&&(l=h.related[i].fields[b].desc?"-"+b:b);break}l=null===f[a+"SortOrder"]?l:f[a+"SortOrder"],c=h.related[j].fields[f[a+"SearchField"]],f[a+"SelectShow"]===!1&&""!==f[a+"SearchValue"]&&void 0!==f[a+"SearchValue"]||f[a+"SelectShow"]&&f[a+"SearchSelectValue"]||c.searchType&&"gtzero"===c.searchType?(f[a+"SearchParams"]=c.sourceModel?c.sourceModel+"__"+c.sourceField+"__":c.searchField?c.searchField+"__":f[a+"SearchField"]+"__",f[a+"SearchParams"]+=!c.searchType||"int"!==c.searchType&&"boolean"!==c.searchType?c.searchType&&"gtzero"===c.searchType?"gt=0":f[a+"SearchType"]+"=":"int=",!c.searchType||"boolean"!==c.searchType&&"select"!==c.searchType?(void 0===c.searchType||"gtzero"===c.searchType)&&(f[a+"SearchParams"]+=encodeURI(f[a+"SearchValue"])):f[a+"SearchParams"]+=f[a+"SearchSelectValue"].value,f[a+"SearchParams"]+=l?"&order_by="+encodeURI(l):""):f[a+"SearchParams"]=l?"order_by="+encodeURI(l):"",f[a+"Page"]=0,k+=k.match(/\/$/)?"?":"&",k+=f[a+"SearchParams"],k+=f[a+"PageSize"]?"&page_size="+f[a+"PageSize"]:"",d({scope:f,set:j,iterator:a,url:k})},f.sort=function(a,b){var c,d,e,g;$("."+a+" .list-header").each(function(){if($(this).attr("id")!==a+"-"+b+"-header"){var c=$(this).find("i");c.attr("class","icon-sort")}}),d=$("#"+a+"-"+b+"-header i"),e="",d.hasClass("icon-sort")?(d.removeClass("icon-sort"),d.addClass("icon-sort-up")):d.hasClass("icon-sort-up")?(d.removeClass("icon-sort-up"),d.addClass("icon-sort-down"),e="-"):d.hasClass("icon-sort-down")&&(d.removeClass("icon-sort-down"),d.addClass("icon-sort-up"));for(g in h.related)h.related[g].iterator===a&&(c=h.related[g].fields[b].sourceModel?e+h.related[g].fields[b].sourceModel+"__"+h.related[g].fields[b].sourceField:e+b);f[a+"SortOrder"]=c,f.search(a)}}}]),angular.module("SearchHelper",["RestServices","Utilities","RefreshHelper"]).factory("SearchInit",["Alert","Rest","Refresh","$location","GetBasePath","Empty","$timeout","Wait","Store",function(a,b,c,d,e,f,g,h,i){return function(a){function b(a){var b,c,d,e;e=void 0===a||1===a?"":a,l[p+"SearchField"+e]="",l[p+"SearchFieldLabel"+e]="";for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&o.fields[c].key){o.fields[c].sourceModel?(d=o.fields[c].sourceModel+"__"+o.fields[c].sourceField,r=o.fields[c].desc?"-"+d:d):r=o.fields[c].desc?"-"+c:c,(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)&&(l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label);break}if(f(l[p+"SearchField"+e]))for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)){l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label;break}l[p+"SearchType"+e]="icontains",l[p+"SearchTypeLabel"+e]="Contains",l[p+"SearchParams"+e]="",l[p+"SearchValue"+e]="",l[p+"SelectShow"+e]=!1,l[p+"HideSearchType"+e]=!1,l[p+"InputDisable"+e]=!1,l[p+"ExtraParms"+e]="",l[p+"ShowStartBtn"+e]=!0,l[p+"HideAllStartBtn"+e]=!1,l[p+"SearchPlaceholder"+e]=o.fields[l[p+"SearchField"+e]]&&o.fields[l[p+"SearchField"+e]].searchPlaceholder?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]:o.fields[l[p+"SearchField"+e]].searchPlaceholder:"Search",l[p+"InputDisable"+e]=o.fields[l[p+"SearchField"+e]]&&"all"===o.fields[l[p+"SearchField"+e]].searchObject?!0:!1,b=l[p+"SearchField"+e],o.fields[b]&&(!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType||(l[p+"SelectShow"+e]=!0,l[p+"SearchSelectOpts"+e]=o.fields[b].searchOptions),o.fields[b].searchType&&"int"===o.fields[b].searchType&&(l[p+"HideSearchType"+e]=!0),o.fields[b].searchType&&"gtzero"===o.fields[b].searchType&&(l[p+"InputHide"+e]=!0))}var e,g,j,k,l=a.scope,m=a.set,n=a.url,o=a.list,p=a.iterator?a.iterator:o.iterator,q=a.setWidgets===!1?!1:!0,r=a.sort_order||"";if(q)for(e=o.searchWidgets?o.searchWidgets:1,g=1;e>=g;g++)j=1===g?"":g,$("#search-widget-container"+j)&&b(g);k={set:m,defaultUrl:n,list:o,iterator:p,sort_order:r},i("CurrentSearchParams",k),l.setSearchField=function(a,b,c,d){var e=void 0===d||1===d?"":d;l[a+"SearchFieldLabel"+e]=c,l[a+"SearchField"+e]=b,l[a+"SearchValue"+e]="",l[a+"SelectShow"+e]=!1,l[a+"HideSearchType"+e]=!1,l[a+"InputHide"+e]=!1,l[a+"SearchType"+e]="icontains",l[a+"InputDisable"+e]="all"===o.fields[b].searchObject?!0:!1,l[a+"ShowStartBtn"+e]=!0,l[a+"SearchPlaceholder"+e]=o.fields[l[a+"SearchField"+e]]&&o.fields[l[a+"SearchField"+e]].searchPlaceholder?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]:o.fields[l[a+"SearchField"+e]].searchPlaceholder:"Search",o.fields[b].searchType&&"gtzero"===o.fields[b].searchType?(l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1,l.search(a)):o.fields[b].searchSingleValue?(l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"SearchSelectValue"+e]="boolean"===o.fields[b].searchType&&"true"===o.fields[b].searchValue?{value:1}:"boolean"===o.fields[b].searchType&&"false"===o.fields[b].searchValue?{value:0}:{value:o.fields[b].searchValue},l[a+"ShowStartBtn"+e]=!1):"in"===o.fields[b].searchType?(l[a+"SearchType"+e]="in",l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1):!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType&&"select_or"!==o.fields[b].searchType?o.fields[b].searchType&&"int"===o.fields[b].searchType?l[a+"SearchType"+e]="int":o.fields[b].searchType&&"isnull"===o.fields[b].searchType&&(l[a+"SearchType"+e]="isnull",l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]="true",l[a+"ShowStartBtn"+e]=!1):(l[a+"SelectShow"+e]=!0,l[a+"SearchSelectOpts"+e]=o.fields[b].searchOptions),l.search(a)},l.resetSearch=function(a){var c,e=o.searchWidgets?o.searchWidgets:1;for(c=1;e>=c;c++)b(c);window.location="/#"+d.path(),l.search(a)},l.removeDoSearch&&l.removeDoSearch(),l.removeDoSearch=l.$on("doSearch",function(a,b,d,e){l[b+"Loading"]=void 0===e||e===!0?!0:!1;var f,g=n;l[b+"Page"]=d?parseInt(d)-1:0,l[b+"SearchParams"]&&(g+=/\/$/.test(g)?"?"+l[b+"SearchParams"]:"&"+l[b+"SearchParams"]),f=/\/$/.test(g)?"?":"&",g+=l[b+"_page_size"]?f+"page_size="+l[b+"_page_size"]:"",d&&(f=/\/$/.test(g)?"?":"&",g+=f+"page="+d),l[b+"ExtraParms"]&&(f=/\/$/.test(g)?"?":"&",g+=f+l[b+"ExtraParms"]),g=g.replace(/\&\&/,"&"),c({scope:l,set:m,iterator:b,url:g})}),l.removePrepareSearch&&l.removePrepareSearch(),l.removePrepareSearch=l.$on("prepareSearch",function(a,b,c,d,e){h("start"),l[b+"SearchParams"]="";var f,g,i=o.searchWidgets?o.searchWidgets:1;for(f=1;i>=f;f++)g=1===f?"":f,$("#search-widget-container"+g)&&o.fields[l[b+"SearchField"+g]]&&o.fields[l[b+"SearchField"+g]].searchObject&&("all"!==o.fields[l[b+"SearchField"+g]].searchObject?(l[b+"HideAllStartBtn"+g]=!1,l[b+"SearchValue"+g]?(l[b+"ShowStartBtn"+g]=!1,l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+g]].searchOnID?"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__id="+l[b+"SearchValue"+g]:"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__name__icontains="+l[b+"SearchValue"+g]):(l[b+"ShowStartBtn"+g]=!0,l[b+"SearchParams"]+="&"+o.fields[l[b+"SearchField"+g]].searchField+"="+o.fields[l[b+"SearchField"+g]].searchObject)):l[b+"HideAllStartBtn"+g]=!0);l.$emit("prepareSearch2",b,c,d,e)}),l.removePrepareSearch2&&l.removePrepareSearch2(),l.removePrepareSearch2=l.$on("prepareSearch2",function(a,b,c,d,e){var g,h,i=o.searchWidgets?o.searchWidgets:1;for(g=1;i>=g;g++)h=1===g?"":g,l[b+"HoldInput"+h]=!0,$("#search-widget-container"+h)&&o.fields[l[b+"SearchField"+h]]&&!o.fields[l[b+"SearchField"+h]].searchObject&&(l[b+"ShowStartBtn"+h]=l[b+"SearchValue"+h]?!1:!0,(!l[b+"SelectShow"+h]&&!f(l[b+"SearchValue"+h])||l[b+"SelectShow"+h]&&l[b+"SearchSelectValue"+h]||o.fields[l[b+"SearchField"+h]]&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+h]].searchField?"&"+o.fields[l[b+"SearchField"+h]].searchField+"__":o.fields[l[b+"SearchField"+h]].sourceModel?"&"+o.fields[l[b+"SearchField"+h]].sourceModel+"__"+o.fields[l[b+"SearchField"+h]].sourceField+"__":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?"&"+l[b+"SearchField"+h]+"__":"&"+l[b+"SearchField"+h]+"__",l[b+"SearchParams"]+=!o.fields[l[b+"SearchField"+h]].searchType||"int"!==o.fields[l[b+"SearchField"+h]].searchType&&"boolean"!==o.fields[l[b+"SearchField"+h]].searchType?o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType?"gt=0":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?l[b+"SearchType"+h]+"=":"iexact=":"int=",!o.fields[l[b+"SearchField"+h]].searchType||"boolean"!==o.fields[l[b+"SearchField"+h]].searchType&&"select"!==o.fields[l[b+"SearchField"+h]].searchType?(!o.fields[l[b+"SearchField"+h]].searchType||o.fields[l[b+"SearchField"+h]].searchType&&"or"!==o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"!==o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=encodeURI(l[b+"SearchValue"+h])):l[b+"SearchParams"]+=l[b+"SearchSelectValue"+h].value));("inventory"===b&&l.inventoryFailureFilter||"host"===b&&l.hostFailureFilter)&&(l[b+"SearchParams"]+="&has_active_failures=true"),r&&(l[b+"SearchParams"]+=l[b+"SearchParams"]?"&":"",l[b+"SearchParams"]+="order_by="+encodeURI(r)),l.$emit("doSearch",b,c,d,e)}),l.startSearch=function(a,b){13===a.keyCode&&l.search(b)},l.search=function(a,b,c){c=void 0===c?!0:!1,c&&(l[m]=[]),l.$emit("prepareSearch",a,b,c)},l.sort=function(a){$(".list-header").each(function(){if($(this).attr("id")!==a+"-header"){var b=$(this).find("i");b.attr("class","fa fa-sort")}});var b=$("#"+a+"-header i"),c="";b.hasClass("fa-sort")?(b.removeClass("fa-sort"),b.addClass("fa-sort-up")):b.hasClass("fa-sort-up")?(b.removeClass("fa-sort-up"),b.addClass("fa-sort-down"),c="-"):b.hasClass("fa-sort-down")&&(b.removeClass("fa-sort-down"),b.addClass("fa-sort-up")),r=o.fields[a].searchField?c+o.fields[a].searchField:o.fields[a].sortField?c+o.fields[a].sortField:o.fields[a].sourceModel?c+o.fields[a].sourceModel+"__"+o.fields[a].sourceField:c+a,l.search(o.iterator)},l.searchCleanup=function(){l.removeDoSearch(),l.removePrepareSearch(),l.removePrepareSearch2()}}}]),angular.module("TeamHelper",["RestServices","Utilities","OrganizationListDefinition","SearchHelper","PaginationHelpers","ListGenerator"]).factory("SetTeamListeners",["Alert","Rest",function(a,b){return function(a){var c=a.scope,d=a.set,e=a.iterator;c.$on("TeamResultFound",function(a,b,f){var g,h,i,j;if(f.length===b.length){for(i="organization",j="organization_name",g=0;gSelect existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.",base:"users",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{},fieldActions:{}}),angular.module("CloudCredentialsListDefinition",[]).value("CloudCredentialList",{name:"cloudcredentials",iterator:"cloudcredential",selectTitle:"Add Cloud Credentials",editTitle:"Cloud Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},team:{label:"Team",ngBind:"credential.team_name",sourceModel:"team",sourceField:"name",excludeModal:!0},user:{label:"User",ngBind:"credential.user_username",sourceModel:"user",sourceField:"username",excludeModal:!0}},actions:{add:{mode:"all",ngClick:"addCredential()","class":"btn-sm",awToolTip:"Create a new credential"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash-o",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("CredentialsListDefinition",[]).value("CredentialList",{name:"credentials",iterator:"credential",selectTitle:"Add Credentials",editTitle:"Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},kind:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0}},actions:{add:{mode:"all",ngClick:"addCredential()",awToolTip:"Create a new credential"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("GroupListDefinition",[]).value("GroupList",{name:"groups",iterator:"group",selectTitle:"Copy Groups",editTitle:"Groups",index:!0,well:!1,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{help:{awPopOver:"Choose groups by clicking on each group you wish to add. Click the Select button to add the groups to the selected inventory group.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Adding Groups"}},fieldActions:{edit:{label:"Edit",ngClick:"editGroup(group.id)",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit group",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteGroup(group.id, group.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete group",dataPlacement:"top"}}}),angular.module("HomeGroupListDefinition",[]).value("HomeGroupList",{name:"home_groups",iterator:"group",editTitle:"Groups",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Group",ngClick:"editGroup(group.id, group.inventory)",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-6 ellipsis"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ /#/inventories/' + group.inventory + '/' }}"},source:{label:"Source",searchType:"select",searchOptions:[{name:"ec2",value:"ec2"},{name:"none",value:""},{name:"rax",value:"rax"}],sourceModel:"inventory_source",sourceField:"source",searchOnly:!0},has_external_source:{label:"Has external source?",searchType:"in",searchValue:"ec2,rax",searchOnly:!0,sourceModel:"inventory_source",sourceField:"source"},has_active_failures:{label:"Has failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},last_update_failed:{label:"Update failed?",searchType:"select",searchSingleValue:!0,searchValue:"failed",searchOnly:!0,sourceModel:"inventory_source",sourceField:"status"},id:{label:"ID",searchOnly:!0}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",awToolTip:"{{ group.status_tooltip }}",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",dataPlacement:"top",ngHref:"/#/inventories/{{ group.inventory }}/",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",ngShow:"(group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate(group.id)",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"(group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{label:"Edit",mode:"all",ngClick:"editGroup(group.id)",awToolTip:"Edit group",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HomeHostListDefinition",[]).value("HomeHostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Name",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-7 ellipsis",ngClick:"editHost(host.id, host.name)"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ '/#/inventories/' + host.inventory }}"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Has failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_inventory_sources:{label:"Has external source?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},id:{label:"ID",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{label:"Edit",ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"}},actions:{stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HostListDefinition",[]).value("HostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,well:!1,fields:{name:{key:!0,label:"Host Name",linkTo:"/inventories/{{ inventory_id }}/hosts/{{ host.id }}"},description:{label:"Description"}},actions:{help:{awPopOver:"Select hosts by clicking on each host you wish to add. Add the selected hosts to the group by clicking the Select button.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Selecting Hosts"}},fieldActions:{edit:{label:"Edit",ngClick:"editHost({{ host.id }})",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit host",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete host",dataPlacement:"top"}}}),angular.module("InventoriesListDefinition",[]).value("InventoryList",{name:"inventories",iterator:"inventory",selectTitle:"Add Inventories",editTitle:"Inventories",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},organization:{label:"Organization",ngBind:"inventory.summary_fields.organization.name",linkTo:"/#/organizations/{{ inventory.organization }}",sourceModel:"organization",sourceField:"name",excludeModal:!0},has_inventory_sources:{label:"Cloud sourced?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_active_failures:{label:"Failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},inventory_sources_with_failures:{label:"Sync failures?",searchType:"gtzero",searchValue:"true",searchOnly:!0}},actions:{add:{mode:"all",ngClick:"addInventory()",awToolTip:"Create a new inventory"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{status:{ngHref:"inventory.status_link",iconClass:"{{ 'fa fa-cloud icon-cloud-' + inventory.status_class }}",awToolTip:"{{ inventory.status_tip }}",dataPlacement:"top"},failed_hosts:{ngHref:"inventory.failed_hosts_link",iconClass:"{{ 'fa icon-failures-' + inventory.failed_hosts_class }}",awToolTip:"{{ inventory.failed_hosts_tip }}",dataPlacement:"top"},edit:{label:"Edit",ngClick:"editInventoryProperties(inventory.id)",awToolTip:"Edit inventory",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteInventory(inventory.id, inventory.names')",awToolTip:"Delete inventory",dataPlacement:"top"}}}),angular.module("InventoryGroupsDefinition",[]).value("InventoryGroups",{name:"groups",iterator:"group",editTitle:"{{ inventory_name }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,filterBy:"{ show: true }","class":"table-condensed table-no-border",fields:{name:{label:"Groups",key:!0,ngClick:"showHosts(group.id,group.group_id, false)",ngClass:"group.selected_class",hasChildren:!0,columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",nosort:!0,awDroppable:"{{ group.isDroppable }}",awDraggable:"{{ group.isDraggable }}",dataContainment:"#groups_table",dataTreeId:"{{ group.id }}",dataGroupId:"{{ group.group_id }}",dataType:"group"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createGroup()",awToolTip:"Create a new group"},properties:{mode:"all",awToolTip:"Edit inventory properties",ngClick:"editInventoryProperties()"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refreshGroups()"},stream:{ngClick:"showGroupActivity()",awToolTip:"View Activity Stream",mode:"all"},help:{mode:"all",awToolTip:"Get help building your inventory",ngClick:"showGroupHelp()",id:"inventory-summary-help"}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",ngShow:"group.id > 1",awToolTip:"{{ group.status_tooltip }}",dataTipWatch:"group.launch_tooltip",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",ngShow:"group.id > 1",dataPlacement:"top",ngClick:"showHosts(group.id, group.group_id, group.show_failures)",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",dataTipWatch:"group.launch_tooltip",ngShow:"group.id > 1 && (group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate({{ group.id }})",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"group.id > 1 && (group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{mode:"all",ngClick:"editGroup({{ group.group_id + ',' + group.id }})",awToolTip:"Edit group",ngShow:"group.id > 1",dataPlacement:"top"},"delete":{mode:"all",ngClick:"deleteGroup({{ group.id + ',' + group.group_id }})",awToolTip:"Delete group",ngShow:"group.id != 1",dataPlacement:"top"}}}),angular.module("InventoryHostsDefinition",[]).value("InventoryHosts",{name:"hosts",iterator:"host",editTitle:"{{ selected_group }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,"class":"table-condensed table-no-border",fields:{name:{key:!0,label:"Hosts",ngClick:"editHost(host.id)",searchPlaceholder:"search_place_holder",columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",dataHostId:"{{ host.id }}",dataType:"host",awDraggable:"true"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"},"delete":{ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash",awToolTip:"Delete host",dataPlacement:"top"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createHost()",ngHide:"selected_tree_id == 1",awToolTip:"Create a new host"},stream:{ngClick:"showHostActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("JobEventsListDefinition",[]).value("JobEventList",{name:"jobevents",iterator:"jobevent",editTitle:"Job Events",index:!1,hover:!0,hasChildren:!0,filterBy:"{ show: true }",navigationLinks:{details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",active:!0,icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",icon:"icon-laptop"}},fields:{created:{label:"Created On",columnClass:"col-lg-1 col-md-1 hidden-sm hidden-xs",key:!0,nosort:!0,searchable:!1,link:!1},status:{label:"Status",showValue:!1,columnClass:"col-sm-1 col-xs-2 text-center",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}],nosort:!0,searchable:!1,ngClick:"viewJobEvent({{ jobevent.id }})",awToolTip:"{{ jobevent.statusBadgeToolTip }}",dataPlacement:"top",badgeIcon:"fa icon-job-{{ jobevent.status }}",badgePlacement:"left",badgeToolTip:"{{ jobevent.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgClick:"viewJobEvent({{ jobevent.id }})"},event_display:{label:"Event",hasChildren:!0,ngClick:"toggleChildren(jobevent.id, jobevent.related.children)",nosort:!0,searchable:!1,ngClass:"{{ jobevent.class }}",appendHTML:"jobevent.event_detail"},host:{label:"Host",ngBind:"jobevent.summary_fields.host.name",ngHref:"{{ jobevent.hostLink }}",searchField:"hosts__name",nosort:!0,searchOnly:!1,id:"job-event-host-header","class":"break",columnClass:"col-lg-2 hidden-sm hidden-xs"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{columnClass:"col-sm-1 col-xs-2",view:{label:"View",ngClick:"viewJobEvent(jobevent.id)",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("JobHostDefinition",[]).value("JobHostList",{name:"jobhosts",iterator:"jobhost",editTitle:"All summaries",index:!0,hover:!0,navigationLinks:{ngHide:"host_id !== null",details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",active:!0,icon:"icon-laptop"}},fields:{job:{label:"Job ID",ngClick:"showJob(jobhost.job)",columnShow:"host_id !== null",key:!0,desc:!0},host:{label:"Host",key:!0,sourceModel:"host",sourceField:"name",ngBind:"jobhost.host_name",ngHref:"jobhost.hostLinkTo"},status:{label:"Status",badgeNgHref:"{{ jobhost.statusLinkTo }}",badgeIcon:"fa icon-job-{{ jobhost.status }}",badgePlacement:"left",badgeToolTip:"{{ jobhost.statusBadgeToolTip }}",badgeTipPlacement:"top",ngHref:"{{ jobhost.statusLinkTo }}",awToolTip:"{{ jobhost.statusBadgeToolTip }}",dataPlacement:"top",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}]},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},ok:{label:"Success",searchable:!1},changed:{label:"Changed",searchable:!1},failures:{label:"Failure",searchable:!0,searchLabel:"Contains failed events?",searchType:"gtzero"},dark:{label:"Unreachable",searchable:!0,searchType:"gtzero",searchLabel:"Contains unreachable hosts?"},skipped:{label:"Skipped",searchable:!1}},actions:{help:{awPopOver:"
\n
Success
Tasks successfully executed on the host.
\n
Changed
Actions taken on the host.
\n
Failure
Tasks that failed on the host.
\n
Unreachable
Times the ansible server could not reach the host.
\n
Skipped
Tasks bypassed and not performed on the host due to prior task failure or the host being unreachable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Job Host Summary",id:"jobhost-help-button"},refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refresh()",ngShow:"host_id == null"}},fieldActions:{}}),angular.module("JobTemplatesListDefinition",[]).value("JobTemplateList",{name:"job_templates",iterator:"job_template",selectTitle:"Add Job Template",editTitle:"Job Templates",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addJobTemplate()",basePaths:["job_templates"],awToolTip:"Create a new template"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editJobTemplate(job_template.id)",icon:"icon-edit",awToolTip:"Edit template","class":"btn-default btn-xs",dataPlacement:"top"},submit:{label:"Launch",icon:"icon-rocket",mode:"all","class":"btn-xs btn-success",ngClick:"submitJob(job_template.id)",awToolTip:"Start a job using this template",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteJobTemplate(job_template.id, job_template.name)",icon:"icon-trash","class":"btn-danger btn-xs",awToolTip:"Delete template",dataPlacement:"top"}}}),angular.module("JobsListDefinition",[]).value("JobList",{name:"jobs",iterator:"job",editTitle:"Jobs",index:!1,hover:!0,"class":"jobs-table",fields:{id:{label:"Job ID",key:!0,desc:!0,searchType:"int"},inventory:{label:"Inventory ID",searchType:"int",searchOnly:!0},created:{label:"Create On",link:!1,searchable:!1},job_template:{label:"Job Template",ngBind:"job.summary_fields.job_template.name",ngHref:"{{ '/#/job_templates/' + job.job_template }}",sourceModel:"job_template",sourceField:"name"},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},status:{label:"Status","class":"job-{{ job.status }}",searchType:"select",linkTo:"{{ job.statusLinkTo }}",searchOptions:[{name:"new",value:"new"},{name:"waiting",value:"waiting"},{name:"pending",value:"pending"},{name:"running",value:"running"},{name:"successful",value:"successful"},{name:"error",value:"error"},{name:"failed",value:"failed"},{name:"canceled",value:"canceled"}],badgeIcon:"fa icon-job-{{ job.status }}",badgePlacement:"left",badgeToolTip:"{{ job.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgHref:"{{ job.statusLinkTo }}",awToolTip:"{{ job.statusBadgeToolTip }}",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{submit:{label:"Relaunch",icon:"icon-rocket",mode:"all",ngClick:"submitJob(job.id, job.summary_fields.job_template.name)",awToolTip:"Start the job",dataPlacement:"top"},cancel:{label:"Stop",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Cancel a running or pending job",ngShow:"job.status == 'pending' || job.status == 'running' || job.status == 'waiting'",dataPlacement:"top"},"delete":{label:"Delete",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Delete the job",ngShow:"job.status != 'pending' && job.status != 'running' && job.status != 'waiting'",dataPlacement:"top"},dropdown:{type:"DropDown",label:"View",icon:"fa-search-plus","class":"btn-default btn-xs",options:[{ngClick:"editJob(job.id, job.summary_fields.job_template.name)",label:"Status"},{ngClick:"viewEvents(job.id, job.summary_fields.job_template.name)",label:"Events",ngHide:"job.status == 'new'"},{ngClick:"viewSummary(job.id, job.summary_fields.job_template.name)",label:"Host Summary",ngHide:"job.status == 'new'"}]}}}),angular.module("OrganizationListDefinition",[]).value("OrganizationList",{name:"organizations",iterator:"organization",selectTitle:"Add Organizations",editTitle:"Organizations",hover:!0,index:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addOrganization()",awToolTip:"Create a new organization"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editOrganization(organization.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit organization",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteOrganization(organization.id, organization.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete organization",dataPlacement:"top"}}}),angular.module("PermissionListDefinition",[]).value("PermissionList",{name:"permissions",iterator:"permission",selectTitle:"Add Permission",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',editTitle:"Permissions",index:!0,well:!0,fields:{name:{key:!0,label:"Name",ngClick:"editPermission(permission.id)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},actions:{add:{mode:"all",ngClick:"addPermission()",awToolTip:"Add a new permission",ngShow:"PermissionAddAllowed"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editPermission(permission.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit permission",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deletePermission(permission.id, permission.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete permission",ngShow:"PermissionAddAllowed",dataPlacement:"top"}}}),angular.module("ProjectsListDefinition",[]).value("ProjectList",{name:"projects",iterator:"project",selectTitle:"Add Project",editTitle:"Projects",selectInstructions:"
Select existing projects by clicking each project or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new project by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",columnClass:"hidden-sm hidden-xs",excludeModal:!0},scm_type:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0},status:{label:"Status",ngClick:"showSCMStatus(project.id)",awToolTip:"View details of last SCM Update",dataPlacement:"top",badgeIcon:"{{ 'fa icon-failures-' + project.badge }}",badgePlacement:"left",searchType:"select",searchOptions:[],excludeModal:!0},last_updated:{label:"Last Updated",type:"date",excludeModal:!0,searchable:!1}},actions:{add:{mode:"all",ngClick:"addProject()",awToolTip:"Create a new project"},help:{awPopOver:"
\n
Updating
A source control update is in progress.
\n
Never Updated
This project has not yet been updated from source control.
\n
Failed
An error occurred during the most recent source control update, click the status text for more information.
\n
Successful
TThe latest source control update completed successfully.
\n
Missing
The previously configured local project directory is missing.
\n
N/A
The project is not linked to source control, so updates are not applicable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all",awToolTip:"Click for help",awTipPlacement:"top"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editProject(project.id)",awToolTip:"Edit project properties",dataPlacement:"top"},scm_update:{label:"Update",ngClick:"SCMUpdate(project.id)",awToolTip:"{{ project.scm_update_tooltip }}",ngClass:"project.scm_type_class",dataPlacement:"top"},cancel:{label:"Stop",ngClick:"cancelUpdate(project.id, project.name)",awToolTip:"Cancel a running SCM update process",ngShow:"project.status == 'updating'",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteProject(project.id, project.name)",awToolTip:"Permanently remove project from the database",ngShow:"project.status !== 'updating'",dataPlacement:"top"}}}),angular.module("StreamListDefinition",[]).value("StreamList",{name:"activities",iterator:"activity",editTitle:"Activity Stream",selectInstructions:"",index:!1,hover:!0,"class":"table-condensed",searchWidgets:3,fields:{timestamp:{label:"Event Time",key:!0,desc:!0,noLink:!0,searchable:!1},user:{label:"Initiated by",ngBindHtml:"activity.user",sourceModel:"actor",sourceField:"username",searchPlaceholder:"Username",searchWidget:1},description:{label:"Action",ngBindHtml:"activity.description",nosort:!0,searchable:!1,columnClass:"col-lg-7"},system_event:{label:"System event",searchOnly:!0,searchType:"isnull",sourceModel:"actor",sourceField:"username",searchWidget:1},all_objects:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All resources",searchWidget:2},credential_search:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Credential name",searchWidget:2,searchField:"object1"},group_search:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Group name",searchWidget:2,searchField:"object1"},host_search:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Host name",searchWidget:2,searchField:"object1"},inventory_search:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Inventory name",searchWidget:2,searchField:"object1"},job_template_search:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Job template name",searchWidget:2,searchField:"object1"},job_search:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:2,searchField:"object1"},organization_search:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Organization name",searchWidget:2,searchField:"object1"},project_search:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Project name",searchWidget:2,searchField:"object1"},user_search:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Primary username",searchWidget:2,searchField:"object1"},all_objects3:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All related resources",searchWidget:3,searchField:"object2"},credential_search3:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Related credential name",searchWidget:3,searchField:"object2"},group_search3:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Related group name",searchWidget:3,searchField:"object2"},host_search3:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Related host name",searchWidget:3,searchField:"object2"},inventory_search3:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Related inventory name",searchWidget:3,searchField:"object2"},job_search3:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:3,searchField:"object2"},job_template_search3:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Related job template name",searchWidget:3,searchField:"object2"},organization_search3:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Related organization name",searchWidget:3,searchField:"object2"},project_search3:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Related project name",searchWidget:3,searchField:"object2"},user_search3:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Related username",searchWidget:3,searchField:"object2"}},actions:{refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refreshStream()"},close:{mode:"all",awToolTip:"Close Activity Stream view",ngClick:"closeStream()"}},fieldActions:{view:{label:"View",ngClick:"showDetail(activity.id)",icon:"fa-zoom-in","class":"btn-default btn-xs",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("TeamsListDefinition",[]).value("TeamList",{name:"teams",iterator:"team",selectTitle:"Add Team",editTitle:"Teams",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"},organization:{label:"Organization",ngBind:"team.organization_name",sourceModel:"organization",sourceField:"name"}},actions:{add:{mode:"all",ngClick:"addTeam()",awToolTip:"Create a new team"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editTeam(team.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit team",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteTeam(team.id, team.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete team",dataPlacement:"top"}}}),angular.module("UserListDefinition",[]).value("UserList",{name:"users",iterator:"user",selectTitle:"Add Users",editTitle:"Users",selectInstructions:"
Select existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.
When available, a brand new user can be created by clicking the green Create New button.
",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{add:{label:"Create New",mode:"all",ngClick:"addUser()",basePaths:["organizations","users"],"class":"btn-xs",awToolTip:"Create a new user"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editUser(user.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit user",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteUser(user.id, user.username)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete user",dataPlacement:"top"}}}),angular.module("InventorySyncStatusWidget",["RestServices","Utilities"]).factory("InventorySyncStatus",["$rootScope","$compile",function(a,b){return function(a){function c(a){var b=a.label,c=a.count,d=a.fail,e=a.link,f=a.fail_link,g="
\n",d+="\n",d+="\n",d+=c({label:"Inventories",count:k.inventories&&k.inventories.total_with_inventory_source?k.inventories.total_with_inventory_source:0,fail:k.inventories&&k.inventories.inventory_failed?k.inventories.inventory_failed:0,link:"/#/inventories/?has_inventory_sources=true",fail_link:"/#/inventories/?inventory_sources_with_failures=true"}),e=0,f=0,k.inventory_sources)for(h in k.inventory_sources)e+=k.inventory_sources[h].total?k.inventory_sources[h].total:0,f+=k.inventory_sources[h].failed?k.inventory_sources[h].failed:0;d+=c({label:"Groups",count:e,fail:f,link:"/#/home/groups/?has_external_source=true",fail_link:"/#/home/groups/?status=failed"});for(h in k.inventory_sources)k.inventory_sources[h].total&&(d+=c({label:k.inventory_sources[h].label,count:k.inventory_sources[h].total?k.inventory_sources[h].total:0,fail:k.inventory_sources[h].failed?k.inventory_sources[h].failed:0,link:"/#/home/groups/?source="+h,fail_link:"/#/home/groups/?status=failed&source="+h}));d+="\n",d+="
\n",e+="\n",e+="\n",f=0,l.scm_types)for(h in l.scm_types)f+=l.scm_types[h].total?l.scm_types[h].total:0;e+=c({label:"Projects",link:"/#/projects",count:f,fail:l.projects&&l.projects.failed?l.projects.failed:0,fail_link:"/#/projects/?status=failed"}),i=[];for(h in l.scm_types)i.push(h);for(i.sort(),d=0;d\n",e+="
\n",e+="
\n",e+="
\n",e+="\n",g=angular.element(document.getElementById(k)),g.html(e),b(g)(j),j.$emit("WidgetLoaded")}}]),angular.module("StreamWidget",["RestServices","Utilities","StreamListDefinition","SearchHelper","PaginationHelpers","RefreshHelper","ListGenerator","StreamWidget","AuthService"]).factory("setStreamHeight",[function(){return function(){var a=$("#stream-content").height(),b=parseInt($("#tab-content-container").css("min-height").replace(/px/,"")),c=a>b?a:b;$("#tab-content-container").css({"min-height":c})}}]).factory("ShowStream",["setStreamHeight","Authorization",function(a){return function(){var b=$("#stream-container");b.css({position:"absolute",top:0,left:0,width:"100%","min-height":"100%","background-color":"#FFF"}),a(),b.show("slide",{direction:"left"},{duration:500,queue:!1})}}]).factory("HideStream",["LoadBreadCrumbs",function(a){return function(){var b=$("#stream-container");b.hide("slide",{direction:"left"},{duration:500,queue:!1}),setTimeout(function(){b.detach(),b.empty(),b.unbind(),$("#tab-content-container").css({"min-height":0})},500),a()}}]).factory("StreamBreadCrumbs",["$rootScope","$location",function(a,b){return function(){a.breadcrumbs=[];var c,d,e,f,g=b.path().split("/");for(g.splice(0,1),e=0;e=f;f++)c+="/"+g[f];for(f=0;f0)for(f=0;e>=f;f++)c+="/"+g[f];else c="/"+g[e];d=g[e],d=d.charAt(0).toUpperCase()+d.slice(1)}a.breadcrumbs.push({path:c,title:d,ngClick:"closeStream('"+c+"')"})}}}]).factory("FixUrl",[function(){return function(a){return a.replace(/\/api\/v1\//,"/#/")}}]).factory("BuildUrl",[function(){return function(a){var b="/#/";switch(a.base){case"group":case"host":b+="home/"+a.base+"s/?id="+a.id;break;case"inventory":b+="inventories/"+a.id+"/";break;default:b+=a.base+"s/"+a.id+"/"}return b}}]).factory("BuildDescription",["FixUrl","BuildUrl",function(a,b){return function(a){function c(a){return a.replace(/^_deleted_\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d+\+\d+:\d+_/,"")}var d,e,f,g,h,i,j,k;d=a.operation,d+=/e$/.test(a.operation)?"d ":"ed ",e=d,f=a.object1,g=a.object2,h=a.summary_fields[f]?a.summary_fields[f][0]:null,i=f===g?a.summary_fields[f][1]:a.summary_fields[g]?a.summary_fields[g][0]:null,("user"===f||"user"===g)&&(a.summary_fields.user[0].name=a.summary_fields.user[0].username),i&&i.name&&!/^_delete/.test(i.name)?(i.base=g,d+=g+' '+i.name+""+("disassociate"===a.operation?" from ":" to "),e+=g+" "+i.name+("disassociate"===a.operation?" from ":" to ")):g&&(j="",i&&i.name&&(j=" "+c(i.name)),d+=g+j+("disassociate"===a.operation?" from ":" to "),e+=g+j+("disassociate"===a.operation?" from ":" to ")),h&&h.name&&!/^\_delete/.test(h.name)?(h.base=f,d+=f+' '+h.name+"",e+=f+" "+h.name):f&&(j="",k="",!h||!h.name||h&&h.name&&/^_delete/.test(h.name)?a.changes&&a.changes.name?"string"==typeof a.changes.name?(j=" "+a.changes.name,k=j):"object"==typeof a.changes.name&&Array.isArray(a.changes.name)&&(j=" "+a.changes.name[0],k=j):"job"===f&&h&&a.changes&&a.changes.job_template?"delete"!==a.operation?(h.base=f,j=' '+h.id+" "+a.changes.job_template+"",k=" "+h.id+" "+a.changes.job_template):(j=" "+h.id+" "+a.changes.job_template,k=j):"job"===f&&h&&("delete"!==a.operation?(h.base=f,j=' '+h.id+"",k=" "+h.id):(j=" "+h.id,k=j)):h&&h.name&&(j=" "+c(h.name),k=j),d+=f+j,e+=f+k),a.description=d,a.description_nolink=e}}]).factory("ShowDetail",["$rootScope","Rest","Alert","GenerateForm","ProcessErrors","GetBasePath","FormatDate","ActivityDetailForm","Empty","Find",function(a,b,c,d,e,f,g,h,i,j){return function(a){var b,c,e,f=a.activity_id,i=a.scope,k=d,l=h,m=j({list:i.activities,key:"id",val:f});m&&(m.changes_stringified=JSON.stringify(m.changes,null," "),b=m.changes_stringified.match(/\n/g),c=b?b.length:1,c=1>c?3:10,l.fields.changes.rows=10,e=k.inject(l,{mode:"edit",modal:!0,related:!1}),e.changes=m.changes_stringified,e.user=(m.summary_fields.actor?m.summary_fields.actor.username:"system")+" on "+g(new Date(m.timestamps)),e.operation=m.description_nolink,e.formModalAction=function(){$("#form-modal").modal("hide")},$("#form-modal").on("show.bs.modal",function(){$("#form-modal-body").css({width:"auto",height:"auto","max-height":"100%"})}),e.formModalActionLabel="OK",e.formModalCancelShow=!1,e.formModalInfo=!1,e.formModalHeader="Event "+m.id,e.$$phase||e.$digest())}}]).factory("Stream",["$rootScope","$location","Rest","GetBasePath","ProcessErrors","Wait","StreamList","SearchInit","PaginateInit","GenerateList","FormatDate","ShowStream","HideStream","BuildDescription","FixUrl","BuildUrl","ShowDetail","StreamBreadCrumbs","setStreamHeight","Find","Store",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){return function(c){var e,f,o,v,w=g,x=d("activity_stream"),y=j,z=b.path().replace(/^\//,"").split("/")[0],A=c.scope,B=u("CurrentSearchParams"),C=c&&c.inventory_name?c.inventory_name:null,D=c&&c.url?c.url:null;a.flashMessage=null,D?x=D:"/home"!==b.path()&&(e="inventories"===z?"inventory":z.replace(/s$/,""),f=b.path().split("/"),f.splice(0,1),f.length>1&&/^\d+/.test(f[f.length-1])?(e=f[f.length-2],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?"+e+"__id="+f[f.length-1]):f.length>1?(e=f[f.length-1],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?or__object1="+e+"&or__object2="+e):x+="?or__object1="+e+"&or__object2="+e),$("#tab-content-container").append('
'),r(),C&&(o=t({list:a.breadcrumbs,key:"title",val:"{{ inventory_name }}"}),o&&(o.title=C)),l(),v=y.inject(w,{mode:"edit",id:"stream-content",searchSize:"col-lg-3",secondWidget:!0,activityStream:!0}),v.streamTitle=c&&c.title?c.title:null,v.closeStream=function(a){m(),v.searchCleanup&&v.searchCleanup(),B&&h({scope:A,set:B.set,list:B.list,url:B.defaultUrl,iterator:B.iterator,sort_order:B.sort_order,setWidgets:!1}),a&&b.path(a)},v.refreshStream=function(){v.search(w.iterator)},v.showDetail=function(a){q({scope:v,activity_id:a})},v.removeStreamPostRefresh&&v.removeStreamPostRefresh(),v.removeStreamPostRefresh=v.$on("PostRefresh",function(){var a,b,c,d,e,f;for(a=0;a'+v.activities[a].summary_fields.actor.username+"":"system",d=/^\_delete/,e=v.activities[a].object1,f=v.activities[a].object2,e&&v.activities[a].summary_fields[e]&&v.activities[a].summary_fields[e].name?d.test(v.activities[a].summary_fields[e].name)?v.activities[a].objects=v.activities[a].summary_fields[e].name:(c=p(v.activities[a].summary_fields.object1),v.activities[a].objects=''+v.activities[a].summary_fields[e].name+""):v.activities[a].object1&&(v.activities[a].objects=v.activities[a].object1),f&&v.activities[a].summary_fields[f]&&v.activities[a].summary_fields[f].name?d.test(v.activities[a].summary_fields.object2.name)?v.activities[a].objects+=","+v.activities[a].summary_fields[f].name:(c=p(v.activities[a].summary_fields.object2),v.activities[a].objects+=', '+v.activities[a].summary_fields[f].name+""):v.activities[a].object2&&(v.activities[a].objects+=", "+v.activities[a].object2),n(v.activities[a]);setTimeout(function(){s()},500)}),h({scope:v,set:w.name,list:w,url:x}),i({scope:v,list:w,url:x}),v.search(w.iterator)}}]),angular.module("AuthService",["ngCookies","Utilities"]).factory("Authorization",["$http","$rootScope","$location","$cookieStore","GetBasePath",function(a,b,c,d,e){return{setToken:function(a,c){d.remove("token"),d.remove("token_expires"),d.remove("userLoggedIn"),d.put("token",a),d.put("token_expires",c),d.put("userLoggedIn",!0),d.put("sessionExpired",!1),b.token=a,b.userLoggedIn=!0,b.token_expires=c,b.sessionExpired=!1},isUserLoggedIn:function(){return void 0===b.userLoggedIn&&(b.userLoggedIn=d.get("userLoggedIn"),b.sessionExpired=d.get("sessionExpired")),b.userLoggedIn},getToken:function(){return b.token?b.token:d.get("token")},retrieveToken:function(b,c){return a({method:"POST",url:e("authtoken"),data:{username:b,password:c}})},logout:function(){var a=angular.element(document.getElementById("main-view")).scope();a.$destroy(),b.$destroy(),d.remove("accordions"),d.remove("token"),d.remove("token_expires"),d.remove("current_user"),d.remove("lastPath"),d.put("userLoggedIn",!1),d.put("sessionExpired",!1),d.remove("lastPath","/home"),b.current_user={},b.license_tested=void 0,b.userLoggedIn=!1,b.sessionExpired=!1,b.token=null,b.token_expires=null,b.lastPath="/home"},getLicense:function(){return a({method:"GET",url:e("config"),headers:{Authorization:"Token "+this.getToken()}})},setLicense:function(a){a.tested=!1,d.put("license",a)},licenseTested:function(){var a,c;return void 0!==b.license_tested?c=b.license_tested:(a=d.get("license"),c=a&&void 0!==a.tested?a.tested:!1),c},getUser:function(){return a({method:"GET",url:"/api/v1/me/",headers:{Authorization:"Token "+this.getToken()}})},setUserInfo:function(a){b.current_user=a.results[0],d.put("current_user",a.results[0])},restoreUserInfo:function(){b.current_user=d.get("current_user")},getUserInfo:function(a){var c;return b.current_user?b.current_user[a]:(this.restoreUserInfo(),c=d.get("current_user"),c[a])}}}]),angular.module("InventoryTree",["Utilities","RestServices","GroupsHelper","PromptDialog"]).factory("SortNodes",[function(){return function(a){var b,c,d=[],e=[];for(b=0;b0?!0:!1,has_inventory_sources:s[e].has_inventory_sources,id:r,source:s[e].summary_fields.inventory_source.source,group_id:s[e].id,event_level:c,children:i,ngicon:s[e].children.length>0?"fa fa-minus-square-o node-toggle":"fa fa-square-o node-no-toggle",ngclick:"toggle("+r+")",related:{children:s[e].children.length>0?s[e].related.children:"",inventory_source:s[e].related.inventory_source},status:s[e].summary_fields.inventory_source.status,status_class:k["class"],status_tooltip:k.tooltip,launch_tooltip:k.launch_tip,launch_class:k.launch_class,hosts_status_tip:n.tooltip,show_failures:n.failures,hosts_status_class:n["class"],selected_class:"",show:!0,isDraggable:!0,isDroppable:!0},q.push(o),p&&o.group_id===p&&(m.selected_tree_id=r,m.selected_group_id=o.group_id),s[e].children.length>0&&j(s[e].children,r,c+1)}}function k(){e("start"),a.setUrl(b("inventory")+l+"/"),a.get().success(function(a){m.$emit("buildAllGroups",a.name,a.related.tree,a.related.groups)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+l+". GET returned: "+b})})}var l=h.inventory_id,m=h.scope,n=h.refresh,o=h.emit,p=h.new_group_id,q=[],r=1;m.buildAllGroupsRemove&&m.buildAllGroupsRemove(),m.buildAllGroupsRemove=m.$on("buildAllGroups",function(b,d,f){a.setUrl(f),a.get().success(function(a){i(a),j(a,0,0),m.autoShowGroupHelp=0===a.length?!0:!1,n?(m.groups=q,m.$emit("GroupTreeRefreshed",d,q,o)):m.$emit("GroupTreeLoaded",d,q,o)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory tree for: "+l+". GET returned: "+b})})}),k()}}]).factory("UpdateGroup",["ApplyEllipsis","GetSyncStatusMsg","Empty",function(a,b,c){return function(d){var e,f,g,h,i,j=d.scope,k=d.group_id,l=d.properties;for(e=0;e\n',m+='
\n',m+='
\n',m+='
\n',m+='\n',m+=1===k.id||0===l.parent?"
Move Group
\n":"
Copy or Move?
\n",m+="
\n",m+='
\n',1===k.id?m+="
Are you sure you want to move group "+l.name+" to the top level?
":0===l.parent?m+="
Are you sure you want to move group "+l.name+" from the top level and make it a child of "+k.name+"?
":(m+='
\n',m+="
Would you like to copy or move group "+l.name+" to group "+k.name+"?
\n",m+="\n",i=angular.element(document.getElementById("inventory-modal-container")),i.empty().append(m),a(i)(j),$("#copy-prompt-modal").modal({backdrop:"static",keyboard:!0,show:!0}),j.moveGroup=function(){var a,b,i;$("#copy-prompt-modal").modal("hide"),e("start"),j.removeGroupRemove&&j.removeGroupRemove(),j.removeGroupRemove=j.$on("removeGroup",function(){l.parent>0?(i=d({list:j.groups,key:"id",val:l.parent}),a=h("base")+"groups/"+i.group_id+"/children/",f.setUrl(a),f.post({id:l.group_id,disassociate:1}).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to remove "+l.name+" from "+i.name+". POST returned status: "+b})})):j.$emit("GroupDeleteCompleted")}),a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id},f.setUrl(a),f.post(b).success(function(){j.$emit("removeGroup")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})},j.copyGroup=function(){$("#copy-prompt-modal").modal("hide"),e("start");var a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id};f.setUrl(a),f.post(b).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})}}}]).factory("CopyMoveHost",["$compile","Alert","ProcessErrors","Find","Wait","Rest","Empty","GetBasePath",function(a,b,c,d,e,f,g,h){return function(b){var g,i,j=b.scope,k=d({list:j.groups,key:"id",val:b.target_tree_id}),l=d({list:j.hosts,key:"id",val:b.host_id}),m=!1,n="";if(l.summary_fields.all_groups)for(i=0;i\n',n+='
URL must begin with ssh, http or https and may not contain '@'
\n"),p+='\n',b.chkPass&&(p+='
Password must be stronger
\n',p+='
\n',p+='
\n',p+='\n',p+="
\n",p+=k({hdr:"Password Complexity",content:'
A password with reasonable strength is required. As you type the password a progress bar will measure the strength. Sufficient strength is reached when the bar turns green.
Password strength is judged using the following:
Minimum 8 characters in length
\n
Contains a sufficient combination of the following items:\n
\n';for(b in this.form.actions)("all"===this.form.actions[b].mode||this.form.actions[b].mode===a.mode)&&(c+=this.button({btn:this.form.actions[b],action:b,toolbar:!0}));return c+="
\n");for(d in this.form.buttons)"object"==typeof this.form.buttons[d]&&(e=this.form.buttons[d],"save"===d&&(e.label="Save",e["class"]="btn-success"),"reset"===d&&(e.label="Reset",e["class"]="btn-default"),p+='\n");p+="
\n"),j=1,k=m.related[g].base?m.related[g].base:g,k=k.replace(/^\//,"");for(d in m.related[g].fields)j++,n+=i({list:m.related[g],fld:d,options:a,base:k});n+='
\n';for(b in f.fields)void 0!==f.fields[b].searchable&&f.fields[b].searchable!==!0||(void 0!==f.fields[b].searchWidget&&1!==f.fields[b].searchWidget||1!==c)&&f.fields[b].searchWidget!==c||(h+='
\n';
+for(j in t.actions)("all"===t.actions[j].mode||t.actions[j].mode===b.mode)&&(void 0===t.actions[j].basePaths||t.actions[j].basePaths&&t.actions[j].basePaths.indexOf(c)>-1)&&(s+=this.button({btn:t.actions[j],action:j,toolbar:!0}));"select"===b.mode&&t.selectInstructions&&(k={awPopOver:t.selectInstructions,dataPlacement:"top",dataContainer:"body","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Help",iconSize:"fa-lg"},s+=this.button({btn:k,action:"help",toolbar:!0})),s+="
\n');for(n in t.fields)void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+='
\n"),o=2,c=t.base?t.base:t.name,c=c.replace(/^\//,"");for(n in t.fields)o++,void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+=h({list:t,fld:n,options:b,base:c}));if("select"===b.mode||"lookup"===b.mode)s+='
\n"),"groups"!==t.name&&(s+=e("lookup"===b.mode||b.id&&"form-modal-body"===b.id?{set:t.name,iterator:t.iterator}:{set:t.name,iterator:t.iterator})),s}}}]),angular.module("PromptDialog",["Utilities"]).factory("Prompt",[function(){return function(a){var b,c=angular.element(document.getElementById("prompt-modal")),d=c.scope();d.promptHeader=a.hdr,d.promptBody=a.body,d.promptAction=a.action,b=null===a["class"]||void 0===a["class"]?"btn-danger":a["class"],$("#prompt_action_btn").removeClass(b).addClass(b),$(c).modal({backdrop:"static",keyboard:!0,show:!0})}}]),String.prototype.strReverse=function(){var a,b="";for(a=0;aA credential must be associated with either a user or a team. Choosing a user allows only the selected user access to the credential. Choosing a team shares the credential with all team members.",dataTitle:"Owner",dataPlacement:"right",dataContainer:"body"},user:{label:"User that owns this credential",type:"lookup",sourceModel:"user",sourceField:"username",ngClick:"lookUpUser()",ngShow:"owner == 'user'",awRequiredWhen:{variable:"user_required",init:"false"}},team:{label:"Team that owns this credential",type:"lookup",sourceModel:"team",sourceField:"name",ngClick:"lookUpTeam()",ngShow:"owner == 'team'",awRequiredWhen:{variable:"team_required",init:"false"}},kind:{label:"Type",excludeModal:!0,type:"select",ngOptions:"kind.label for kind in credential_kind_options",ngChange:"kindChange()",addRequired:!0,editRequired:!0,helpCollapse:[{hdr:"Select a Credential Type",content:"
\n
AWS
\n
Access keys for Amazon Web Services used for inventory management or deployment.
\n
Machine
\n
Authentication for remote machine access. This can include SSH keys, usernames, passwords, and sudo information. Machine credentials are used when submitting jobs to run playbooks against remote hosts.
Rackspace
\n
Access information for Rackspace Cloud used for inventory management or deployment.
\n
SCM
\n
Used to check out and synchronize playbook repositories with a remote source control management system such as Git, Subversion (svn), or Mercurial (hg). These credentials are used on the Projects tab.
Click on the regions field to see a list of regions for your cloud provider. You can select multiple regions, or choose All to include all regions. Tower will only be updated with Hosts associated with the selected regions.
Override variables found in ec2.ini and used by the inventory update script. For a detailed description of these variables view ec2.ini in the Ansible github repo.
Enter variables using either JSON or YAML syntax. Use the radio button to toggle between the two.
If checked, all variables for child groups and hosts will be removed and replaced by those found on the external source.
When not checked a merge will be performed, combining local variables with those found on the external source.
",dataTitle:"Overwrite Variables",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"update_on_launch",label:"Update on Launch",type:"checkbox",ngShow:"source.value !== '' && source.value !== null",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this inventory, refresh the inventory from the selected source before executing job tasks.
",dataTitle:"Update on Launch",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{labelClass:"col-lg-3",controlClass:"col-lg-5",save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("HostGroupsFormDefinition",[]).value("HostGroupsForm",{editTitle:"Host Groups",name:"host",well:!1,formLabelSize:"col-lg-3",formFieldSize:"col-lg-9",fields:{groups:{label:"Groups",type:"select",multiple:!0,ngOptions:"group.name for group in inventory_groups",addRequired:!0,editRequired:!0,awPopOver:"
Provide a host name, ip address, or ip address:port. Examples include:
',dataTitle:"Inventory Variables",dataPlacement:"right",dataContainer:"body"}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("JobEventDataDefinition",[]).value("JobEventDataForm",{editTitle:"{{ id }} - {{ event_display }}",name:"job_events",well:!1,"class":"horizontal-narrow",fields:{event_data:{label:!1,type:"textarea",readonly:!0,rows:18,"class":"modal-input-xxlarge"}}}),angular.module("JobEventsFormDefinition",[]).value("JobEventsForm",{name:"job_events",well:!1,forceListeners:!0,fields:{status:{labelClass:"job-{{ status }}",type:"custom",section:"Event",control:'
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",awRequiredWhen:{variable:"playbookrequired",init:"true"},column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
The number of parallel or simultaneous processes to use while executing the playbook. 0 signifies the default value from the ansible configuration file.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
',dataTitle:"Limit",dataPlacement:"right",dataContainer:"body"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting the Tower server using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",addRequired:!0,editRequired:!0,column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
For more information and examples see the Selecting Targets section under Inventory and Patterns in the Ansible documentation.
',dataContainer:"body",dataTitle:"Limit",dataPlacement:"right"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting Tower using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
A project must have at least one organization. Pick one organization now to create the project, and then after the project is created you can add additional organizations.
Only super users and organization administrators are allowed to make changes to projects. Associating one or more organizations to a project determins which organizations admins have access to modify the project.",dataTitle:"Organization",dataContainer:"body",dataPlacement:"right"},scm_type:{label:"SCM Type",type:"select",ngOptions:"type.label for type in scm_type_options",ngChange:"scmChange()",addRequired:!0,editRequired:!0},missing_path_alert:{type:"alertblock","class":"alert-info",ngShow:"showMissingPlaybooksAlert && scm_type.value == ''",alertTxt:'
WARNING: There are no unassigned playbook directories in the base project path {{ base_dir }}. Either the projects directory is empty, or all of the contents are already assigned to other projects. New projects can be checked out from source control by changing the SCM type option rather than specifying checkout paths manually. To continue with manual setup, log into the Tower host and ensure content is present in a subdirectory under {{ base_dir }}. Run "chown -R awx" on the content directory to ensure Tower can read the playbooks.
',closeable:!1},base_dir:{label:"Project Base Path",type:"textarea",showonly:!0,ngShow:"scm_type.value == ''",awPopOver:"
Base path used for locating playbooks. Directories found inside this path will be listed in the playbook directory drop-down. Together the base path and selected playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
",dataTitle:"Project Base Path",dataContainer:"body",dataPlacement:"right"},local_path:{label:"Playbook Directory",type:"select",id:"local-path-select",ngOptions:"path.label for path in project_local_paths",awRequiredWhen:{variable:"pathRequired",init:!1},ngShow:"scm_type.value == '' && !showMissingPlaybooksAlert",awPopOver:"
Select from the list of directories found in the base path.Together the base path and the playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
Note: If using SSH protocol for GitHub or Bitbucket, enter in the SSH key only, do not enter a username (other than git). Additionally, GitHub and Bitbucket do not support password authentication when using SSH protocol. GIT read only protocol (git://) does not use username or password information.',show:"scm_type.value == 'git'"},{hdr:"SVN URLs",content:'
Note: Mercurial does not support password authentication for SSH. If applicable, add the username, password and key below. Do not put the username and key in the URL. If using Bitbucket and SSH, do not supply your Bitbucket username.',show:"scm_type.value == 'hg'"}]},scm_branch:{labelBind:"scmBranchLabel",type:"text",ngShow:"scm_type && scm_type.value !== ''",addRequired:!1,editRequired:!1},credential:{label:"SCM Credential",type:"lookup",ngShow:"scm_type && scm_type.value !== ''",sourceModel:"credential",sourceField:"name",ngClick:"lookUpCredential()",addRequired:!1,editRequired:!1},checkbox_group:{label:"SCM Update Options",type:"checkbox_group",ngShow:"scm_type && scm_type.value !== ''",fields:[{name:"scm_clean",label:"Clean",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Remove any local modifications prior to performing an update.
",dataTitle:"SCM Clean",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_delete_on_update",label:"Delete on Update",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Delete the local repository in its entirety prior to performing an update.
Depending on the size of the repository this may significantly increase the amount of time required to complete an update.
",dataTitle:"SCM Delete",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_update_on_launch",label:"Update on Launch",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this project, perform an update to the local repository prior to starting the job.
",dataTitle:"SCM Update",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{add:{ngClick:"add('organizations')",icon:"icon-plus",label:"Add",awToolTip:"Add an organization"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('organizations', organization.id, organization.name)",icon:"icon-edit",awToolTip:"Edit the organization","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('organizations', organization.id, organization.name, 'organizations')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the organization"}}}}}),angular.module("TeamFormDefinition",[]).value("TeamForm",{addTitle:"Create Team",editTitle:"{{ name }}",name:"team",well:!0,collapse:!0,collapseTitle:"Team Settings",collapseMode:"edit",collapseOpen:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{name:{label:"Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!1},description:{label:"Description",type:"text",addRequired:!1,editRequired:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",awRequiredWhen:{variable:"teamrequired",init:"true"}}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",add:"Add a new credential"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Modify the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{add:{ngClick:"add('projects')",icon:"icon-plus",label:"Add"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('projects', project.id, project.name)",icon:"icon-edit",awToolTip:"Modify the project","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('projects', project.id, project.name, 'projects')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the project"}}},users:{type:"collection",title:"Users",iterator:"user",open:!1,actions:{add:{ngClick:"add('users')",icon:"icon-plus",label:"Add",awToolTip:"Add a user"}},fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('users', user.id, user.username)",icon:"icon-edit",awToolTip:"Edit user","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('users', user.id, user.username, 'users')",icon:"icon-terash","class":"btn-danger",awToolTip:"Remove user"}}}}}),angular.module("UserFormDefinition",[]).value("UserForm",{addTitle:"Create User",editTitle:"{{ username }}",name:"user",well:!0,forceListeners:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{first_name:{label:"First Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},last_name:{label:"Last Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},email:{label:"Email",type:"email",addRequired:!0,editRequired:!0,autocomplete:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",excludeMode:"edit",awRequiredWhen:{variable:"orgrequired",init:!0}},username:{label:"Username",type:"text",awRequiredWhen:{variable:"not_ldap_user",init:!0},autocomplete:!1},password:{label:"Password",type:"password",ngShow:"ldap_user == false",addRequired:!0,editRequired:!1,ngChange:"clearPWConfirm('password_confirm')",autocomplete:!1,chkPass:!0},password_confirm:{label:"Confirm Password",type:"password",ngShow:"ldap_user == false",addRequired:!1,editRequired:!1,awPassMatch:!0,associated:"password",autocomplete:!1},is_superuser:{label:"Superuser (User has full system administration privileges.)",type:"checkbox",trueValue:"true",falseValue:"false","default":"false",ngShow:"current_user['is_superuser'] == true"},ldap_user:{label:"Created by LDAP",type:"checkbox",readonly:!0}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",awToolTip:"Add a credential for this user"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Edit the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},admin_of_organizations:{type:"collection",title:"Admin of Organizations",iterator:"adminof",open:!1,base:"/organizations",actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},teams:{type:"collection",title:"Teams",iterator:"team",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}}}}),angular.module("InventoryGroupsHelpDefinition",[]).value("InventoryGroupsHelp",{story:{hdr:"Building your inventory",width:510,height:560,steps:[{intro:"Start by creating a group:",img:{src:"groups001.png",maxWidth:338,maxHeight:222},box:'Click on the groups list (the left side of the page) to add a new group.',autoOffNotice:!0},{intro:"Enter group properties:",img:{src:"groups002.png",maxWidth:443,maxHeight:251},box:'Enter the group name, a description and any inventory variables. Variables can be entered using either JSON or YAML syntax. For more on inventory variables, see docs.ansible.com/intro_inventory.html'},{intro:"Cloud inventory: select cloud source",img:{src:"groups003.png",maxWidth:412,maxHeight:215},box:'For a cloud inventory, choose the cloud provider from the list and select your credentials. If you have not already setup credentials for the provider, you will need to do that first on the Credentials tab.'},{intro:"Cloud inventory: synchronize Tower with the cloud",img:{src:"groups004.png",maxWidth:261,maxHeight:221},box:'To pull the cloud inventory into Tower, initiate an inventory sync by clicking .'},{intro:"Groups can have subgroups:",img:{src:"groups005.png",maxWidth:430,maxHeight:206},box:'
First, select a group. Then click to create a new group. The new group will be added to the selected group.
'},{intro:"Copy or move groups:",img:{src:"groups006.png",maxWidth:263,maxHeight:211},box:'
Copy or move a group by dragging and dropping its name onto another group name. A dialog will appear asking if the group should be coppied or moved.
Your Ansible Tower license has reached capacity for the number of managed hosts allowed. You will not be able to add any additional hosts.
"+i,c(d,f,g,null,!0)))}}]),angular.module("ChildrenHelper",["RestServices","Utilities"]).factory("ToggleChildren",[function(){return function(a){function b(a){var b;for(i[a].ngicon="fa fa-minus-square-o node-toggle",b=a+1;b10?10:i,i=3>i?3:i,f.fields[h].rows=i);break;case"results":if(a.event_data&&a.event_data.res&&void 0===a.event_data.res[h])delete f.fields[h];else if(Array.isArray(a.event_data.res[h])&&0!==a.event_data.res[h].length){for(j="",c=0;c10?10:i,i=3>i?3:i,f.fields[h].rows=i)}else delete f.fields[h];break;case"module_name":case"module_args":a.event_data&&a.event_data.res&&(void 0===a.event_data.res.invocation||void 0===a.event_data.res.invocation[h])&&delete f.fields[h]}b=d.inject(f,{mode:"edit",modal:!0,related:!1}),d.reset(),b.formModalAction=function(){$("#form-modal").modal("hide")},b.formModalActionLabel="OK",b.formModalCancelShow=!1,b.formModalInfo="View JSON",$("#form-modal .btn-success").removeClass("btn-success").addClass("btn-none"),$("#form-modal").addClass("skinny-modal"),b.formModalHeader=a.event_display.replace(/^\u00a0*/g,""),b.formModalInfoAction=function(){var b=g,c=b.inject(l,{mode:"edit",modal:!0,related:!1,modal_selector:"#form-modal2",modal_body_id:"form-modal2-body",modal_title_id:"formModal2Header"});b.reset(),c.formModal2Header=a.event_display.replace(/^\u00a0*/g,""),c.event_data=JSON.stringify(a.event_data,null," "),c.formModal2ActionLabel="OK",c.formModal2CancelShow=!1,c.formModal2Info=!1,c.formModalInfo="View JSON",c.formModal2Action=function(){$("#form-modal2").modal("hide")},$("#form-modal2 .btn-success").removeClass("btn-success").addClass("btn-none")},"string"==typeof a.event_data.res&&(b.traceback=a.event_data.res);for(h in f.fields)switch(h){case"status":b.status=a.failed?"error":a.changed?"changed":"success";break;case"created":n=new Date(a.created),b.created=k(n);break;case"host":a.summary_fields&&a.summary_fields.host&&(b.host=a.summary_fields.host.name);break;case"id":case"task":case"play":b[h]=a[h];break;case"start":case"end":a.event_data&&a.event_data.res&&!m(a.event_data.res[h])&&(b[h]=a.event_data.res[h]);break;case"results":if(Array.isArray(a.event_data.res[h])&&a.event_data.res[h].length>0){for(j="",c=0;c button.',"alert-info"):(f("start"),a.setUrl(l.related.inventory_source),a.get().success(function(a){var b=a.related.current_update?a.related.current_update:a.related.last_update;d({group_name:a.summary_fields.group.name,last_update:b,license_error:a.summary_fields.last_update&&a.summary_fields.last_update.license_error?!0:!1,tree_id:j,group_id:k,parent_scope:i})}).error(function(a,c){f("stop"),b(i,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+l.related.inventory_source+" POST returned status: "+c})})))}}]).factory("GetHostsStatusMsg",[function(){return function(a){var b,c,d,e=a.active_failures,f=a.total_hosts;return e>0?(b=f+(1===f?" host":" hosts")+". "+e+" with failed jobs.",d="true",c=!0):(c=!1,0===f?(b="Group contains 0 hosts.",d="na"):(b=f+(1===f?" host":" hosts")+". No job failures",d="false")),{tooltip:b,failures:c,"class":d}}}]).factory("GetSyncStatusMsg",[function(){return function(a){var b,c,d,e=a.status,f="",g="Start sync process";switch(b=e,c="icon-cloud-"+b,e){case"never updated":b="never",c="icon-cloud-na disabled",d='Sync not performed. Click to start it now.';break;case"none":case"":f="btn-disabled",b="n/a",c="icon-cloud-na disabled",d='Cloud source not configured. Click to update.',g=d;break;case"failed":d="Sync failed. Click to view log.";break;case"successful":d="Sync completed. Click to view log.";break;case"updating":d="Sync running"}return{"class":c,tooltip:d,status:b,launch_class:f,launch_tip:g}}}]).factory("SourceChange",["GetBasePath","CredentialList","LookUpInit","Empty",function(a,b,c,d){return function(e){var f,g,h=e.scope,i=e.form;d(h.source)||("file"===h.source.value?h.sourcePathRequired=!0:(h.sourcePathRequired=!1,h.source_path="",h[i.name+"_form"].source_path.$setValidity("required",!0)),"rax"===h.source.value?(h.source_region_choices=h.rax_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])):"ec2"===h.source.value&&(h.source_region_choices=h.ec2_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])),("rax"===h.source.value||"ec2"===h.source.value)&&(f="rax"===h.source.value?"rax":"aws",g=a("credentials")+"?cloud=true&kind="+f,c({url:g,scope:h,form:i,list:b,field:"credential"})))}}]).factory("GroupsCancelUpdate",["Rest","ProcessErrors","Alert","Wait","Find",function(a,b,c,d,e){return function(f){var g,h=f.scope,i=f.tree_id;h.removeCancelUpdate&&h.removeCancelUpdate(),h.removeCancelUpdate=h.$on("CancelUpdate",function(e,f){a.setUrl(f),a.post().success(function(){d("stop"),c("Inventory Sync Cancelled",'Your request to cancel the sync process was submitted to the task manger. Click the button to monitor the status.',"alert-info")}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+f+" failed. POST status: "+c})})}),h.removeCheckCancel&&h.removeCheckCancel(),h.removeCheckCancel=h.$on("CheckCancel",function(e,f,g){var i=g?g:f;i+="cancel/",a.setUrl(i),a.get().success(function(a){a.can_cancel?h.$emit("CancelUpdate",i):(d("stop"),c("Cancel Inventory Sync",'Either you do not have access or the sync process completed. Click the button to view the latest status.',"alert-info"))}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+i+" failed. GET status: "+c})})}),g=e({list:h.groups,key:"id",val:i}),h.selected_tree_id=g.id,h.selected_group_id=g.group_id,!g||"updating"!==g.status&&"pending"!==g.status?c("Cancel Inventory Sync",'The sync process completed. Click the to view the latest status.',"alert-info"):(d("start"),a.setUrl(g.related.inventory_source),a.get().success(function(a){h.$emit("CheckCancel",a.related.last_update,a.related.current_update)}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+g.related.inventory_source+" failed. GET status: "+c})}))}}]).factory("GroupsAdd",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","ParseTypeChange","GroupsEdit","Wait","GetChoices","GetSourceTypeOptions","LookUpInit","BuildTree","SourceChange","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){return function(b){var c,d=b.inventory_id,i=void 0!==b.group_id?b.group_id:null,m=b.scope,q=null!==i?k("groups")+i+"/children/":k("inventory")+d+"/groups/",u=g,v=h,w=v.inject(u,{mode:"add",modal:!0,related:!1,show_modal:!1});$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),w.formModalActionLabel="Save",w.formModalCancelShow=!0,w.parseType="yaml",w.source=null,l(w),v.reset(),w.removeAddTreeRefreshed&&w.removeAddTreeRefreshed(),w.removeAddTreeRefreshed=w.$on("GroupTreeRefreshed",function(){a.formModalHeader=null,a.formModalCancleShow=null,a.formModalActionLabel=null,n("stop"),$("#form-modal").modal("hide"),w.removeAddTreeRefreshed()}),w.removeSaveComplete&&w.removeSaveComplete(),w.removeSaveComplete=w.$on("SaveComplete",function(a,b,c){c||(w.searchCleanup&&w.searchCleanup(),w.formModalActionDisabled=!1,r({scope:m,inventory_id:d,refresh:!0,new_group_id:b}),t())}),w.removeFormSaveSuccess&&w.removeFormSaveSuccess(),w.removeFormSaveSuccess=w.$on("formSaveSuccess",function(a,b,c){var d,g,h,i,k=!1,l={};if(null!==w.source.value&&""!==w.source.value){for(l.group=b,l.source=w.source.value,l.source_path=w.source_path,l.credential=w.credential,l.overwrite=w.overwrite,l.overwrite_vars=w.overwrite_vars,l.update_on_launch=w.update_on_launch,d=$("#s2id_group_source_regions").select2("data"),g=[],h=0;h"+A.summary_fields.group.name+". Use the Refresh button to monitor the status.","alert-info"):o({scope:A,group_id:d,url:A.group_update_url,group_name:A.name,group_source:A.source.value})},A.sourceChange=function(){v({scope:A,form:g})}}}]).factory("GroupsDelete",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","Wait","BuildTree","Find",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){return function(a){var b,c=a.scope,d=a.tree_id,f=a.inventory_id,g=n({list:c.groups,key:"id",val:d}),h=k("inventory")+f+"/groups/";b=function(){$("#prompt-modal").on("hidden.bs.modal",function(){l("start")}),$("#prompt-modal").modal("hide"),e.setUrl(h),e.post({id:g.group_id,disassociate:1}).success(function(){$("#prompt-modal").off(),c.$emit("GroupDeleteCompleted")}).error(function(a,b){l("stop"),j(c,a,b,null,{hdr:"Error!",msg:"Call to "+h+" failed. POST returned status: "+b})})},i({hdr:"Delete Group",body:"
Are you sure you want to delete group "+g.name+"?
",action:b,"class":"btn-danger"})}}]).factory("ShowUpdateStatus",["$rootScope","$location","$log","$routeParams","Rest","Alert","GenerateForm","Prompt","ProcessErrors","GetBasePath","FormatDate","InventoryStatusForm","Wait","Empty","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){return function(a){function b(a){var b,d;return b=a.match(/\n/g),d=b?b.length:1,d>c?c:d}var c,d,h,j,n,p,q,r=a.group_name,s=a.last_update,t=g,u=l,v=a.license_error;void 0===s||null===s||""===s?(m("stop"),f("Missing Configuration","The selected group is not configured for inventory sync. Edit the group and provide Source information.","alert-info")):(d='
\n
\n',$("#inventory-modal-container").empty().append(d),h=t.inject(u,{mode:"edit",id:"form-container",breadCrumbs:!1,related:!1}),j=$(document).width(),n=$("body").height(),j>1199?(p=675,q=750>n?n-20:750,c=18):1199>=j&&j>=768?(p=550,q=620>n?n-15:620,c=12):(p=j-20,q=500>n?n:500,c=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:p,height:q,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#inventory-modal-container").empty(),o()},open:function(){m("stop")}}),e.setUrl(s),e.get().success(function(a){for(var c in u.fields)a[c]&&(h[c]="created"===c?k(new Date(a[c])):a[c]);h.license_error=v,h.status_rows=b(a.status),h.stdout_rows=b(a.result_stdout),h.traceback_rows=b(a.result_traceback),$("#status-modal-dialog").dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(h,a,b,null,{hdr:"Error!",msg:"Failed to retrieve last update: "+s+". GET status: "+b})}))}}]),angular.module("HostsHelper",["RestServices","Utilities","ListGenerator","HostListDefinition","SearchHelper","PaginationHelpers","ListGenerator","AuthService","HostsHelper","InventoryHelper","RelatedSearchHelper","InventoryFormDefinition","SelectionHelper","HostGroupsFormDefinition"]).factory("SetEnabledMsg",[function(){return function(a){a.enabledToolTip=a.has_inventory_sources?a.enabled?"Host is available":"Host is not available":a.enabled?"Host is available. Click to toggle.":"Host is not available. Click to toggle."}}]).factory("SetHostStatus",["SetEnabledMsg",function(a){return function(b){b.activeFailuresLink="/#/hosts/"+b.id+"/job_host_summaries/?inventory="+b.inventory+"&host_name="+encodeURI(b.name),b.has_active_failures===!0?(b.badgeToolTip="Most recent job failed. Click to view jobs.",b.active_failures="failed"):b.has_active_failures===!1&&null===b.last_job?(b.has_active_failures="none",b.badgeToolTip="No job data available.",b.active_failures="n/a"):b.has_active_failures===!1&&null!==b.last_job&&(b.badgeToolTip="Most recent job successful. Click to view jobs.",b.active_failures="success"),b.enabled_flag=b.enabled,a(b)}}]).factory("SetStatus",["SetEnabledMsg","Empty",function(a,b){return function(c){function d(a){return a.length>25?a.substr(0,25)+"...":a}function e(a){var b,c,e;if(a.has_active_failures===!0||a.has_active_failures===!1&&null!==a.last_job)if(a.has_active_failures===!0?(a.badgeToolTip="Most recent job failed. Click to view jobs.",a.active_failures="failed"):(a.badgeToolTip="Most recent job successful. Click to view jobs.",a.active_failures="success"),a.summary_fields.recent_jobs.length>0){for(e=a.summary_fields.recent_jobs.sort(function(a,b){return-1*(a-b)}),h="Recent Jobs",g='
";else a.has_active_failures===!1&&null===a.last_job&&(a.has_active_failures="none",a.badgeToolTip="No job data available.",a.active_failures="n/a");a.job_status_html=g,a.job_status_title=h}var f,g,h,i=c.scope,j=c.host;if(b(j))for(f=0;fAre you sure you want to delete host "+j+" from group "+n.name+"?":"
\n",d=j("hosts")+l+"/",f=o.inject(null,{mode:"edit",modal:!0,related:!1,html:c}),b=0;bGroups',f.formModalCancelShow=!0,f.formModalActionDisabled=!0,$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),f.hostGroupChangeRemove&&f.hostGroupChangeRemove(),f.hostGroupChangeRemove=f.$on("hostGroupChange",function(){p.pop(),0===p.length&&(h=function(){setTimeout(function(){m("stop")},500)},k({scope:f,inventory_id:n,group_id:f.group_id,action:h}))}),f.formModalAction=function(){var a,b,c;for($("#form-modal").modal("hide"),m("start"),a=0;a0?(f.assignedGroups=null,f.leftButtonDisabled=!0,f.rightButtonDisabled=!1):f.rightButtonDisabled=!0},f.rightChange=function(){null!==f.assignedGroups&&f.assignedGroups.length>0?(f.selectedGroups=null,f.leftButtonDisabled=!1,f.rightButtonDisabled=!0):f.leftButtonDisabled=!0},f.moveLeft=function(){var a,b,c,d;for(a=0;af.available_groups[b].name.toLowerCase()&&f.assignedGroups[a].name.toLowerCase()f.host_groups[b].name.toLowerCase()&&f.selectedGroups[a].name.toLowerCase()0){for(j("stop"),u+='\n",m=angular.element(document.getElementById("password-body")),m.html(u),c(m.contents())(q),$("#password-modal").modal(),$("#password-modal").on("shown.bs.modal",function(){$("#password-body").find('input[type="password"]:first').focus()})}else q.startJob()}}]).factory("SubmitJob",["PromptPasswords","$compile","Rest","$location","GetBasePath","CredentialList","LookUpInit","CredentialForm","ProcessErrors","JobTemplateForm","Wait",function(a,b,c,d,e,f,g,h,i,j,k){return function(b){function l(b){var e,f,g;m.credentialWatchRemove&&m.credentialWatchRemove(),e=(new Date).toISOString(),f=b.related.jobs?b.related.jobs:b.related.job_template+"jobs/",g=o?o:b.name,k("start"),c.setUrl(f),c.post({name:g+" "+e,description:b.description,job_template:b.id,inventory:b.inventory,project:b.project,playbook:b.playbook,credential:b.credential,forks:b.forks,limit:b.limit,verbosity:b.verbosity,extra_vars:b.extra_vars}).success(function(b){m.job_id=b.id,b.passwords_needed_to_start.length>0?a({scope:m,passwords:b.passwords_needed_to_start,start_url:b.related.start,form:h}):(c.setUrl(b.related.start),c.post().success(function(){k("stop");var a=d.path().replace(/^\//,"").split("/")[0];"jobs"===a?m.refresh():d.path("/jobs")}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to start job. POST returned status: "+b})}))}).error(function(a,b){k("stop"),i(m,a,b,null,{hdr:"Error!",msg:"Failed to create job. POST returned status: "+b})})}var m=b.scope,n=b.id,o=b.template?b.template:null,p=d.path().replace(/^\//,"").split("/")[0],q=e(p)+n+"/";k("start"),c.setUrl(q),c.get().success(function(a){m.credential="",""===a.credential||null===a.credential?(k("stop"),m.credentialWatchRemove&&m.credentialWatchRemove(),m.credentialWatchRemove=m.$watch("credential",function(b,c){b!==c&&""!==m.credential&&null!==m.credential&&void 0!==m.credential&&(a.credential=m.credential,l(a))}),g({scope:m,form:j,current_item:null,list:f,field:"credential",hdr:"Credential Required"}),m.lookUpCredential()):l(a)}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to get job template details. GET returned status: "+b})})}}]).factory("ProjectUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","ProjectsForm","Wait",function(a,b,c,d,e,f,g,h,i){return function(b){var d=b.scope,j=b.project_id,k=e("projects")+j+"/update/";d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(){i("stop"),g("Update Started","The request to start the SCM update process was submitted. To monitor the update status, refresh the page by clicking the Refresh button.","alert-info"),d.refresh()}),d.removeSCMSubmit&&d.removeSCMSubmit(),d.removeSCMSubmit=d.$on("SCMSubmit",function(b,c,e){a({scope:d,passwords:c,start_url:k,form:h,extra_html:e})}),i("start"),c.setUrl(k),c.get().success(function(a){var b,c;if(i("stop"),a.can_update){for(c="",b=0;b\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="\n",d.projects[b].scm_username&&(c+='
\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="
\n");break}c+="",d.$emit("SCMSubmit",a.passwords_needed_to_update,c)}else g("Permission Denied","You do not have access to update this project. Please contact your system administrator.","alert-danger")}).error(function(a,b){f(d,a,b,null,{hdr:"Error!",msg:"Failed to get project update details: "+k+" GET status: "+b})})}}]).factory("InventoryUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","GroupForm","BuildTree","Wait",function(a,b,c,d,e,f,g,h,i,j){return function(b){var d=b.scope,e=b.url,i=b.group_id,k=b.tree_id;d.removeHostReloadComplete&&d.removeHostReloadComplete(),d.removeHostReloadComplete=d.$on("HostReloadComplete",function(){j("stop"),g("Update Started",'Your request to start the inventory sync process was submitted. Monitor progress by clicking the button.',"alert-info"),d.removeHostReloadComplete&&d.removeHostReloadComplete()}),d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(a,b){"started"===b&&(d.refreshGroups?(d.selected_tree_id=k,d.selected_group_id=i,d.refreshGroups()):d.refresh&&d.refresh(),d.$emit("HostReloadComplete"))}),d.removeInventorySubmit&&d.removeInventorySubmit(),d.removeInventorySubmit=d.$on("InventorySubmit",function(b,c,f){a({scope:d,passwords:c,start_url:e,form:h,extra_html:f})}),j("start"),c.setUrl(e),c.get().success(function(a){a.can_update?d.$emit("InventorySubmit",a.passwords_needed_to_update):(j("stop"),g("Permission Denied","You do not have access to run the update. Please contact your system administrator.","alert-danger"))}).error(function(a,b){j("stop"),f(d,a,b,null,{hdr:"Error!",msg:"Failed to get inventory_source details. "+e+"GET status: "+b})})}}]),angular.module("JobsHelper",["Utilities","FormGenerator","JobSummaryDefinition","InventoryHelper"]).factory("JobStatusToolTip",[function(){return function(a){var b;switch(a){case"successful":case"success":b="There were no failed tasks.";break;case"failed":b="Some tasks encountered errors.";break;case"canceled":b="Stopped by user request.";break;case"new":b="In queue, waiting on task manager.";break;case"waiting":b="SCM Update or Inventory Update is executing.";break;case"pending":b="Not in queue, waiting on task manager.";break;case"running":b="Playbook tasks executing."}return b}}]).factory("ShowJobSummary",["Rest","Wait","GetBasePath","FormatDate","ProcessErrors","GenerateForm","JobSummary","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h){return function(i){function j(a){var b=a.match(/\n/g),c=b?b.length:1;return c>p?20:c}var k,l,m,n,o,p,q,r,s=i.job_id,t=f,u=g;r='
Only allow the user or team to view the inventory.
\n
Write
\n
Allow the user or team to modify hosts and groups contained in the inventory, add new hosts and groups, and perform inventory sync operations.\n
Admin
\n
Allow the user or team full access to the inventory. This includes reading, writing, deletion of the inventory and inventory sync operations.
\n
\n"):(b.projectrequired=!0,b.permissionTypeHelp="
\n
Run
\n
Allow the user or team to perform a live deployment of the project against the inventory. In Run mode modules will be executed, and changes to the inventory will occur.
\n
Check
\n
Only allow the user or team to deploy the project against the inventory as a dry-run operation. In Check mode, module operations will only be simulated. No changes will occur.
\n
\n"),c&&(b.permission_type="Inventory"===b.category?"read":"run")}}]),angular.module("ProjectPathHelper",["RestServices","Utilities"]).factory("GetProjectPath",["Alert","Rest","GetBasePath","ProcessErrors",function(a,b,c,d){return function(a){function e(a){var b,c,d=[],e=[];for(b=0;b\n',$("#projects-modal-container").empty().append(b),c=q.inject(r,{mode:"edit",id:"form-container",related:!1,breadCrumbs:!1}),q.reset(),d=$(document).width(),f=$("body").height(),d>1199?(h=675,j=750>f?f-20:750,n=20):1199>=d&&d>=768?(h=550,j=620>f?f-15:620,n=15):(h=d-20,j=500>f?f:500,n=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:h,height:j,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#projects-modal-container").empty()},open:function(){m("stop")}}),e.setUrl(p),e.get().success(function(a){var b,d=a;for(b in r.fields)d[b]?c[b]="created"===b?k(new Date(d[b])):d[b]:d.summary_fields.project[b]&&(c[b]=d.summary_fields.project[b]);$("#status-modal-dialog").dialog({title:d.summary_fields.project.name+" Status"}).dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(c,a,b,r,{hdr:"Error!",msg:"Failed to retrieve status of project: "+o+". GET status: "+b})})}}]),angular.module("SelectionHelper",["Utilities","RestServices"]).factory("SelectionInit",["Rest","Alert","ProcessErrors","ReturnToCaller","Wait",function(a,b,c,d,e){return function(b){var f,g=b.scope,h=b.list,i=b.url,j=b.returnToCaller;f=void 0!==b.selected?b.selected:[],g.formModalActionDisabled=!0,g.disableSelectBtn=!0,g["toggle_"+h.iterator]=function(a,b){var c,d,e;for(c=0;c0?(g.formModalActionDisabled=!1,g.disableSelectBtn=!1):(g.formModalActionDisabled=!0,g.disableSelectBtn=!0)},g.finishSelection=function(){function b(){f=[],void 0!==j?d(j):($("#form-modal").modal("hide"),g.$emit("modalClosed"))}function k(b){a.post(b).success(function(a,b){m.push({result:"success",data:a,status:b}),g.$emit("callFinished")}).error(function(a,b,c){m.push({result:"error",data:a,status:b,headers:c}),g.$emit("callFinished")})}a.setUrl(i);var l,m=[];if(g.formModalActionDisabled=!0,g.disableSelectBtn=!0,e("start"),g.callFinishedRemove&&g.callFinishedRemove(),g.callFinishedRemove=g.$on("callFinished",function(){var a,d=0;if(m.length===f.length){for(e("stop"),a=0;a0)for(l=0;lh)h++,setTimeout(1e3,e());else if("success"===g.status)return d(a)}var f,g={},h=0;return null===c.apiDefaults||void 0===c.apiDefaults?(f="/api/v1/",b.setUrl(f),b.get().success(function(a){var b,d=a;for(b in d)switch(b){case"organizations":d[b].iterator="organization";break;case"jobs":d[b].iterator="job";break;case"users":d[b].iterator="user";break;case"teams":d[b].iterator="team";break;case"hosts":d[b].iterator="host";break;case"groups":d[b].iterator="group";break;case"projects":d[b].iterator="project";break;case"inventories":d[b].iterator="inventory"}c.apiDefaults=d,g={status:"success"}}).error(function(a,b){g={status:"error",msg:"Call to "+f+" failed. GET returned status: "+b}}),e()):d(a)}}]),angular.module("InventoryHelper",["RestServices","Utilities","OrganizationListDefinition","ListGenerator","AuthService","InventoryHelper","InventoryFormDefinition","ParseHelper","SearchHelper"]).factory("WatchInventoryWindowResize",["ApplyEllipsis",function(a){return function(){var b;$(window).resize(function(){clearTimeout(b),b=setTimeout(function(){$("#groups_table .name-column").each(function(){var a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%";$(this).find(".group-name").css({width:e})}),a("#groups_table .group-name a"),a("#hosts_table .host-name a")},100)})}}]).factory("SaveInventory",["InventoryForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","Wait",function(a,b,c,d,e,f,g,h,i){return function(e){var f,h,j,k=e.scope,l=a,m=g("inventory");i("start");try{if(h="json"===k.inventoryParseType?JSON.parse(k.inventory_variables):jsyaml.load(k.inventory_variables),"object"!=typeof h)throw"failed to return an object!";j={};for(f in l.fields)"inventory_variables"!==f&&(l.fields[f].realName?j[l.fields[f].realName]=k[f]:j[f]=k[f]);b.setUrl(m+k.inventory_id+"/"),b.put(j).success(function(a){k.inventory_variables?(b.setUrl(a.related.variable_data),b.put(h).success(function(){i("stop"),k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory varaibles. PUT returned status: "+b})})):k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory. POST returned status: "+b})})}catch(n){i("stop"),c("Error","Error parsing inventory variables. Parser returned: "+n)}}}]).factory("EditInventoryProperties",["InventoryForm","GenerateForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","SaveInventory","Wait","Store","SearchInit",function(a,b,c,d,e,f,g,h,i,j,k,l,m){return function(n){var o,p=n.scope,q=n.inventory_id,r=b,s=a,t={},u=l("CurrentSearchParams");s.well=!1,o=r.inject(s,{mode:"edit",modal:!0,related:!1,modal_show:!1}),s.well=!0,i(o,"inventory_variables","inventoryParseType"),o.inventoryParseType="yaml",o.formModalActionLabel="Save",o.formModalCancelShow=!0,o.formModalInfo=!1,o.formModalHeader="Inventory Properties",k("start"),c.setUrl(h("inventory")+q+"/"),c.get().success(function(a){var b,c;for(b in s.fields){if("inventory_variables"===b){if($.isEmptyObject(a.variables)||"{}"===a.variables||"null"===a.variables||""===a.variables)o.inventory_variables="---";else try{c=JSON.parse(a.variables),o.inventory_variables=jsyaml.safeDump(c)}catch(e){d("Variable Parse Error","Attempted to parse variables for inventory: "+q+". Parse returned: "+e),console&&(console.log(e),console.log("data:"),console.log(a.variables)),o.inventory_variables="---"}t.inventory_variables=o.variables}else"inventory_name"===b?(o[b]=a.name,t[b]=o[b]):"inventory_description"===b?(o[b]=a.description,t[b]=o[b]):a[b]&&(o[b]=a[b],t[b]=o[b]);s.fields[b].sourceModel&&a.summary_fields&&a.summary_fields[s.fields[b].sourceModel]&&(o[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField],t[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField])}f({scope:o,form:s,current_item:o.organization,list:g,field:"organization"}),k("stop"),$("#form-modal").modal("show")}).error(function(a,b){e(o,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+q+". GET returned: "+b})}),o.removeInventorySaved&&o.removeInventorySaved(),o.removeInventorySaved=o.$on("InventorySaved",function(){$("#form-modal").modal("hide"),o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1}),p.$emit("RefreshInventories")}),o.cancelModal=function(){o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1})},o.formModalAction=function(){p.inventory_id=q,p.inventory_name=o.inventory_name,j({scope:o})}}}]),angular.module("md5Helper",["RestServices","Utilities"]).factory("md5Setup",[function(){return function(a){var b=a.scope,c=a.master,d=a.check_field,e=a.default_val;b[d]=e,c[d]=e,b.genMD5=function(a){var c=new Date;b[a]=$.md5("AnsibleWorks"+c.getTime())},b.toggleCallback=function(a){"false"===b.allow_callbacks&&(b[a]="")},b.selectAll=function(a){$('input[name="'+a+'"]').focus().select()}}}]),angular.module("RefreshRelatedHelper",["RestServices","Utilities","PaginationHelpers"]).factory("RefreshRelated",["ProcessErrors","Rest","Wait","PageRangeSetup",function(a,b,c,d){return function(e){var f=e.scope,g=e.set,h=e.iterator,i=e.url;b.setUrl(i),b.get().success(function(a){d({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[g]=a.results,f[h+"Loading"]=!1,f[h+"HoldInput"]=!1,c("stop"),f.$emit("related"+g)}).error(function(b,c){a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RefreshHelper",["RestServices","Utilities","PaginationHelpers"]).factory("Refresh",["ProcessErrors","Rest","Wait","Empty","PageRangeSetup",function(a,b,c,d,e){return function(d){var f=d.scope,g=d.set,h=d.iterator,i=d.url;f.current_url=i,b.setUrl(i),b.get().success(function(a){var b,d;for(e({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[h+"Loading"]=!1,b=1;3>=b;b++)d=1===b?"":b,f[h+"HoldInput"+d]=!1;f[g]=a.results,window.scrollTo(0,0),c("stop"),f.$emit("PostRefresh")}).error(function(b,c){f[h+"HoldInput"]=!1,a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RelatedSearchHelper",["RestServices","Utilities","RefreshRelatedHelper"]).factory("RelatedSearchInit",["$timeout","Alert","Rest","RefreshRelated","Wait",function(a,b,c,d,e){return function(a){function b(a){var b,c,d,e;for(e in h.related)if("tree"!==h.related[e].type&&(void 0===a||a===h.related[e].iterator)){b=h.related[e].iterator;for(d in h.related[e].fields)if(h.related[e].fields[d].key){f[b+"SearchField"]=d,f[b+"SearchFieldLabel"]=h.related[e].fields[d].label;break}f[b+"SortOrder"]=null,f[b+"SearchType"]="icontains",f[b+"SearchTypeLabel"]="Contains",f[b+"SearchValue"]=null,f[b+"SelectShow"]=!1,f[b+"ShowStartBtn"]=!0,f[b+"HideAllStartBtn"]=!1,c=f[b+"SearchField"],!h.related[e].fields[c].searchType||"boolean"!==h.related[e].fields[c].searchType&&"select"!==h.related[e].fields[c].searchType||(f[b+"SelectShow"]=!0,f[b+"SearchSelectOpts"]=h.fields[c].searchOptions),h.related[e].fields[c].searchType&&"gtzero"===h.related[e].fields[c].searchType&&(f[b+"InputHide"]=!0)}}var c,f=a.scope,g=a.relatedSets,h=a.form;b(),f.resetSearch=function(a){b(a),f.search(a)},f.setSearchField=function(a,b,c){var d,e;for(e in h.related)h.related[e].iterator===a&&(d=h.related[e].fields[b]);f[a+"SearchFieldLabel"]=c,f[a+"SearchField"]=b,f[a+"SearchValue"]="",f[a+"SelectShow"]=!1,f[a+"InputHide"]=!1,f[a+"ShowStartBtn"]=!0,void 0!==d.searchType&&"gtzero"===d.searchType&&(f[a+"InputHide"]=!0,f[a+"ShowStartBtn"]=!1),void 0===d.searchType||"boolean"!==d.searchType&&"select"!==d.searchType||(f[a+"SelectShow"]=!0,f[a+"SearchSelectOpts"]=d.searchOptions),void 0!==d.searchType&&"int"===d.searchType&&(f[a+"SearchType"]="int"),f.search(a)},f.setSearchType=function(a,b,c){f[a+"SearchTypeLabel"]=c,f[a+"SearchType"]=b,f.search(a)},f.startSearch=function(a,b){13===a.keyCode&&f.search(b)},f.search=function(a){e("start"),f[a+"Loading"]=!0,f[a+"HoldInput"]=!0,f[a+"SearchValue"]&&(f[a+"ShowStartBtn"]=!1),"host"===a&&"has_active_failures"===f.hostSearchField&&(f.hostFailureFilter=f.hostSearchSelectValue&&1===f.hostSearchSelectValue.value?!0:!1);var b,i,j,k,l;for(i in g)if(g[i].iterator===a){j=i,k=g[i].url;for(b in h.related[i].fields)h.related[i].fields[b].key&&(l=h.related[i].fields[b].desc?"-"+b:b);break}l=null===f[a+"SortOrder"]?l:f[a+"SortOrder"],c=h.related[j].fields[f[a+"SearchField"]],f[a+"SelectShow"]===!1&&""!==f[a+"SearchValue"]&&void 0!==f[a+"SearchValue"]||f[a+"SelectShow"]&&f[a+"SearchSelectValue"]||c.searchType&&"gtzero"===c.searchType?(f[a+"SearchParams"]=c.sourceModel?c.sourceModel+"__"+c.sourceField+"__":c.searchField?c.searchField+"__":f[a+"SearchField"]+"__",f[a+"SearchParams"]+=!c.searchType||"int"!==c.searchType&&"boolean"!==c.searchType?c.searchType&&"gtzero"===c.searchType?"gt=0":f[a+"SearchType"]+"=":"int=",!c.searchType||"boolean"!==c.searchType&&"select"!==c.searchType?(void 0===c.searchType||"gtzero"===c.searchType)&&(f[a+"SearchParams"]+=encodeURI(f[a+"SearchValue"])):f[a+"SearchParams"]+=f[a+"SearchSelectValue"].value,f[a+"SearchParams"]+=l?"&order_by="+encodeURI(l):""):f[a+"SearchParams"]=l?"order_by="+encodeURI(l):"",f[a+"Page"]=0,k+=k.match(/\/$/)?"?":"&",k+=f[a+"SearchParams"],k+=f[a+"PageSize"]?"&page_size="+f[a+"PageSize"]:"",d({scope:f,set:j,iterator:a,url:k})},f.sort=function(a,b){var c,d,e,g;$("."+a+" .list-header").each(function(){if($(this).attr("id")!==a+"-"+b+"-header"){var c=$(this).find("i");c.attr("class","icon-sort")}}),d=$("#"+a+"-"+b+"-header i"),e="",d.hasClass("icon-sort")?(d.removeClass("icon-sort"),d.addClass("icon-sort-up")):d.hasClass("icon-sort-up")?(d.removeClass("icon-sort-up"),d.addClass("icon-sort-down"),e="-"):d.hasClass("icon-sort-down")&&(d.removeClass("icon-sort-down"),d.addClass("icon-sort-up"));for(g in h.related)h.related[g].iterator===a&&(c=h.related[g].fields[b].sourceModel?e+h.related[g].fields[b].sourceModel+"__"+h.related[g].fields[b].sourceField:e+b);f[a+"SortOrder"]=c,f.search(a)}}}]),angular.module("SearchHelper",["RestServices","Utilities","RefreshHelper"]).factory("SearchInit",["Alert","Rest","Refresh","$location","GetBasePath","Empty","$timeout","Wait","Store",function(a,b,c,d,e,f,g,h,i){return function(a){function b(a){var b,c,d,e;e=void 0===a||1===a?"":a,l[p+"SearchField"+e]="",l[p+"SearchFieldLabel"+e]="";for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&o.fields[c].key){o.fields[c].sourceModel?(d=o.fields[c].sourceModel+"__"+o.fields[c].sourceField,r=o.fields[c].desc?"-"+d:d):r=o.fields[c].desc?"-"+c:c,(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)&&(l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label);break}if(f(l[p+"SearchField"+e]))for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)){l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label;break}l[p+"SearchType"+e]="icontains",l[p+"SearchTypeLabel"+e]="Contains",l[p+"SearchParams"+e]="",l[p+"SearchValue"+e]="",l[p+"SelectShow"+e]=!1,l[p+"HideSearchType"+e]=!1,l[p+"InputDisable"+e]=!1,l[p+"ExtraParms"+e]="",l[p+"ShowStartBtn"+e]=!0,l[p+"HideAllStartBtn"+e]=!1,l[p+"SearchPlaceholder"+e]=o.fields[l[p+"SearchField"+e]]&&o.fields[l[p+"SearchField"+e]].searchPlaceholder?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]:o.fields[l[p+"SearchField"+e]].searchPlaceholder:"Search",l[p+"InputDisable"+e]=o.fields[l[p+"SearchField"+e]]&&"all"===o.fields[l[p+"SearchField"+e]].searchObject?!0:!1,b=l[p+"SearchField"+e],o.fields[b]&&(!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType||(l[p+"SelectShow"+e]=!0,l[p+"SearchSelectOpts"+e]=o.fields[b].searchOptions),o.fields[b].searchType&&"int"===o.fields[b].searchType&&(l[p+"HideSearchType"+e]=!0),o.fields[b].searchType&&"gtzero"===o.fields[b].searchType&&(l[p+"InputHide"+e]=!0))}var e,g,j,k,l=a.scope,m=a.set,n=a.url,o=a.list,p=a.iterator?a.iterator:o.iterator,q=a.setWidgets===!1?!1:!0,r=a.sort_order||"";if(q)for(e=o.searchWidgets?o.searchWidgets:1,g=1;e>=g;g++)j=1===g?"":g,$("#search-widget-container"+j)&&b(g);k={set:m,defaultUrl:n,list:o,iterator:p,sort_order:r},i("CurrentSearchParams",k),l.setSearchField=function(a,b,c,d){var e=void 0===d||1===d?"":d;l[a+"SearchFieldLabel"+e]=c,l[a+"SearchField"+e]=b,l[a+"SearchValue"+e]="",l[a+"SelectShow"+e]=!1,l[a+"HideSearchType"+e]=!1,l[a+"InputHide"+e]=!1,l[a+"SearchType"+e]="icontains",l[a+"InputDisable"+e]="all"===o.fields[b].searchObject?!0:!1,l[a+"ShowStartBtn"+e]=!0,l[a+"SearchPlaceholder"+e]=o.fields[l[a+"SearchField"+e]]&&o.fields[l[a+"SearchField"+e]].searchPlaceholder?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]:o.fields[l[a+"SearchField"+e]].searchPlaceholder:"Search",o.fields[b].searchType&&"gtzero"===o.fields[b].searchType?(l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1,l.search(a)):o.fields[b].searchSingleValue?(l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"SearchSelectValue"+e]="boolean"===o.fields[b].searchType&&"true"===o.fields[b].searchValue?{value:1}:"boolean"===o.fields[b].searchType&&"false"===o.fields[b].searchValue?{value:0}:{value:o.fields[b].searchValue},l[a+"ShowStartBtn"+e]=!1):"in"===o.fields[b].searchType?(l[a+"SearchType"+e]="in",l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1):!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType&&"select_or"!==o.fields[b].searchType?o.fields[b].searchType&&"int"===o.fields[b].searchType?l[a+"SearchType"+e]="int":o.fields[b].searchType&&"isnull"===o.fields[b].searchType&&(l[a+"SearchType"+e]="isnull",l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]="true",l[a+"ShowStartBtn"+e]=!1):(l[a+"SelectShow"+e]=!0,l[a+"SearchSelectOpts"+e]=o.fields[b].searchOptions),l.search(a)},l.resetSearch=function(a){var c,e=o.searchWidgets?o.searchWidgets:1;for(c=1;e>=c;c++)b(c);window.location="/#"+d.path(),l.search(a)},l.removeDoSearch&&l.removeDoSearch(),l.removeDoSearch=l.$on("doSearch",function(a,b,d,e){l[b+"Loading"]=void 0===e||e===!0?!0:!1;var f,g=n;l[b+"Page"]=d?parseInt(d)-1:0,l[b+"SearchParams"]&&(g+=/\/$/.test(g)?"?"+l[b+"SearchParams"]:"&"+l[b+"SearchParams"]),f=/\/$/.test(g)?"?":"&",g+=l[b+"_page_size"]?f+"page_size="+l[b+"_page_size"]:"",d&&(f=/\/$/.test(g)?"?":"&",g+=f+"page="+d),l[b+"ExtraParms"]&&(f=/\/$/.test(g)?"?":"&",g+=f+l[b+"ExtraParms"]),g=g.replace(/\&\&/,"&"),c({scope:l,set:m,iterator:b,url:g})}),l.removePrepareSearch&&l.removePrepareSearch(),l.removePrepareSearch=l.$on("prepareSearch",function(a,b,c,d,e){h("start"),l[b+"SearchParams"]="";var f,g,i=o.searchWidgets?o.searchWidgets:1;for(f=1;i>=f;f++)g=1===f?"":f,$("#search-widget-container"+g)&&o.fields[l[b+"SearchField"+g]]&&o.fields[l[b+"SearchField"+g]].searchObject&&("all"!==o.fields[l[b+"SearchField"+g]].searchObject?(l[b+"HideAllStartBtn"+g]=!1,l[b+"SearchValue"+g]?(l[b+"ShowStartBtn"+g]=!1,l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+g]].searchOnID?"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__id="+l[b+"SearchValue"+g]:"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__name__icontains="+l[b+"SearchValue"+g]):(l[b+"ShowStartBtn"+g]=!0,l[b+"SearchParams"]+="&"+o.fields[l[b+"SearchField"+g]].searchField+"="+o.fields[l[b+"SearchField"+g]].searchObject)):l[b+"HideAllStartBtn"+g]=!0);l.$emit("prepareSearch2",b,c,d,e)}),l.removePrepareSearch2&&l.removePrepareSearch2(),l.removePrepareSearch2=l.$on("prepareSearch2",function(a,b,c,d,e){var g,h,i=o.searchWidgets?o.searchWidgets:1;for(g=1;i>=g;g++)h=1===g?"":g,l[b+"HoldInput"+h]=!0,$("#search-widget-container"+h)&&o.fields[l[b+"SearchField"+h]]&&!o.fields[l[b+"SearchField"+h]].searchObject&&(l[b+"ShowStartBtn"+h]=l[b+"SearchValue"+h]?!1:!0,(!l[b+"SelectShow"+h]&&!f(l[b+"SearchValue"+h])||l[b+"SelectShow"+h]&&l[b+"SearchSelectValue"+h]||o.fields[l[b+"SearchField"+h]]&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+h]].searchField?"&"+o.fields[l[b+"SearchField"+h]].searchField+"__":o.fields[l[b+"SearchField"+h]].sourceModel?"&"+o.fields[l[b+"SearchField"+h]].sourceModel+"__"+o.fields[l[b+"SearchField"+h]].sourceField+"__":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?"&"+l[b+"SearchField"+h]+"__":"&"+l[b+"SearchField"+h]+"__",l[b+"SearchParams"]+=!o.fields[l[b+"SearchField"+h]].searchType||"int"!==o.fields[l[b+"SearchField"+h]].searchType&&"boolean"!==o.fields[l[b+"SearchField"+h]].searchType?o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType?"gt=0":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?l[b+"SearchType"+h]+"=":"iexact=":"int=",!o.fields[l[b+"SearchField"+h]].searchType||"boolean"!==o.fields[l[b+"SearchField"+h]].searchType&&"select"!==o.fields[l[b+"SearchField"+h]].searchType?(!o.fields[l[b+"SearchField"+h]].searchType||o.fields[l[b+"SearchField"+h]].searchType&&"or"!==o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"!==o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=encodeURI(l[b+"SearchValue"+h])):l[b+"SearchParams"]+=l[b+"SearchSelectValue"+h].value));("inventory"===b&&l.inventoryFailureFilter||"host"===b&&l.hostFailureFilter)&&(l[b+"SearchParams"]+="&has_active_failures=true"),r&&(l[b+"SearchParams"]+=l[b+"SearchParams"]?"&":"",l[b+"SearchParams"]+="order_by="+encodeURI(r)),l.$emit("doSearch",b,c,d,e)}),l.startSearch=function(a,b){13===a.keyCode&&l.search(b)},l.search=function(a,b,c){c=void 0===c?!0:!1,c&&(l[m]=[]),l.$emit("prepareSearch",a,b,c)},l.sort=function(a){$(".list-header").each(function(){if($(this).attr("id")!==a+"-header"){var b=$(this).find("i");b.attr("class","fa fa-sort")}});var b=$("#"+a+"-header i"),c="";b.hasClass("fa-sort")?(b.removeClass("fa-sort"),b.addClass("fa-sort-up")):b.hasClass("fa-sort-up")?(b.removeClass("fa-sort-up"),b.addClass("fa-sort-down"),c="-"):b.hasClass("fa-sort-down")&&(b.removeClass("fa-sort-down"),b.addClass("fa-sort-up")),r=o.fields[a].searchField?c+o.fields[a].searchField:o.fields[a].sortField?c+o.fields[a].sortField:o.fields[a].sourceModel?c+o.fields[a].sourceModel+"__"+o.fields[a].sourceField:c+a,l.search(o.iterator)},l.searchCleanup=function(){l.removeDoSearch(),l.removePrepareSearch(),l.removePrepareSearch2()}}}]),angular.module("TeamHelper",["RestServices","Utilities","OrganizationListDefinition","SearchHelper","PaginationHelpers","ListGenerator"]).factory("SetTeamListeners",["Alert","Rest",function(a,b){return function(a){var c=a.scope,d=a.set,e=a.iterator;c.$on("TeamResultFound",function(a,b,f){var g,h,i,j;if(f.length===b.length){for(i="organization",j="organization_name",g=0;gSelect existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.",base:"users",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{},fieldActions:{}}),angular.module("CloudCredentialsListDefinition",[]).value("CloudCredentialList",{name:"cloudcredentials",iterator:"cloudcredential",selectTitle:"Add Cloud Credentials",editTitle:"Cloud Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},team:{label:"Team",ngBind:"credential.team_name",sourceModel:"team",sourceField:"name",excludeModal:!0},user:{label:"User",ngBind:"credential.user_username",sourceModel:"user",sourceField:"username",excludeModal:!0}},actions:{add:{mode:"all",ngClick:"addCredential()","class":"btn-sm",awToolTip:"Create a new credential"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash-o",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("CredentialsListDefinition",[]).value("CredentialList",{name:"credentials",iterator:"credential",selectTitle:"Add Credentials",editTitle:"Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},kind:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0}},actions:{add:{mode:"all",ngClick:"addCredential()",awToolTip:"Create a new credential"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("GroupListDefinition",[]).value("GroupList",{name:"groups",iterator:"group",selectTitle:"Copy Groups",editTitle:"Groups",index:!0,well:!1,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{help:{awPopOver:"Choose groups by clicking on each group you wish to add. Click the Select button to add the groups to the selected inventory group.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Adding Groups"}},fieldActions:{edit:{label:"Edit",ngClick:"editGroup(group.id)",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit group",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteGroup(group.id, group.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete group",dataPlacement:"top"}}}),angular.module("HomeGroupListDefinition",[]).value("HomeGroupList",{name:"home_groups",iterator:"group",editTitle:"Groups",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Group",ngClick:"editGroup(group.id, group.inventory)",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-6 ellipsis"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ /#/inventories/' + group.inventory + '/' }}"},source:{label:"Source",searchType:"select",searchOptions:[{name:"ec2",value:"ec2"},{name:"none",value:""},{name:"rax",value:"rax"}],sourceModel:"inventory_source",sourceField:"source",searchOnly:!0},has_external_source:{label:"Has external source?",searchType:"in",searchValue:"ec2,rax",searchOnly:!0,sourceModel:"inventory_source",sourceField:"source"},has_active_failures:{label:"Has failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},last_update_failed:{label:"Update failed?",searchType:"select",searchSingleValue:!0,searchValue:"failed",searchOnly:!0,sourceModel:"inventory_source",sourceField:"status"},id:{label:"ID",searchOnly:!0}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",awToolTip:"{{ group.status_tooltip }}",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",dataPlacement:"top",ngHref:"/#/inventories/{{ group.inventory }}/",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",ngShow:"(group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate(group.id)",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"(group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{label:"Edit",mode:"all",ngClick:"editGroup(group.id)",awToolTip:"Edit group",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HomeHostListDefinition",[]).value("HomeHostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Name",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-7 ellipsis",ngClick:"editHost(host.id, host.name)"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ '/#/inventories/' + host.inventory }}"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Has failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_inventory_sources:{label:"Has external source?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},id:{label:"ID",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{label:"Edit",ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"}},actions:{stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HostListDefinition",[]).value("HostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,well:!1,fields:{name:{key:!0,label:"Host Name",linkTo:"/inventories/{{ inventory_id }}/hosts/{{ host.id }}"},description:{label:"Description"}},actions:{help:{awPopOver:"Select hosts by clicking on each host you wish to add. Add the selected hosts to the group by clicking the Select button.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Selecting Hosts"}},fieldActions:{edit:{label:"Edit",ngClick:"editHost({{ host.id }})",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit host",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete host",dataPlacement:"top"}}}),angular.module("InventoriesListDefinition",[]).value("InventoryList",{name:"inventories",iterator:"inventory",selectTitle:"Add Inventories",editTitle:"Inventories",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},organization:{label:"Organization",ngBind:"inventory.summary_fields.organization.name",linkTo:"/#/organizations/{{ inventory.organization }}",sourceModel:"organization",sourceField:"name",excludeModal:!0},has_inventory_sources:{label:"Cloud sourced?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_active_failures:{label:"Failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},inventory_sources_with_failures:{label:"Sync failures?",searchType:"gtzero",searchValue:"true",searchOnly:!0}},actions:{add:{mode:"all",ngClick:"addInventory()",awToolTip:"Create a new inventory"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{status:{ngHref:"inventory.status_link",iconClass:"{{ 'fa fa-cloud icon-cloud-' + inventory.status_class }}",awToolTip:"{{ inventory.status_tip }}",dataPlacement:"top"},failed_hosts:{ngHref:"inventory.failed_hosts_link",iconClass:"{{ 'fa icon-failures-' + inventory.failed_hosts_class }}",awToolTip:"{{ inventory.failed_hosts_tip }}",dataPlacement:"top"},edit:{label:"Edit",ngClick:"editInventoryProperties(inventory.id)",awToolTip:"Edit inventory",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteInventory(inventory.id, inventory.names')",awToolTip:"Delete inventory",dataPlacement:"top"}}}),angular.module("InventoryGroupsDefinition",[]).value("InventoryGroups",{name:"groups",iterator:"group",editTitle:"{{ inventory_name }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,filterBy:"{ show: true }","class":"table-condensed table-no-border",fields:{name:{label:"Groups",key:!0,ngClick:"showHosts(group.id,group.group_id, false)",ngClass:"group.selected_class",hasChildren:!0,columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",nosort:!0,awDroppable:"{{ group.isDroppable }}",awDraggable:"{{ group.isDraggable }}",dataContainment:"#groups_table",dataTreeId:"{{ group.id }}",dataGroupId:"{{ group.group_id }}",dataType:"group"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createGroup()",awToolTip:"Create a new group"},properties:{mode:"all",awToolTip:"Edit inventory properties",ngClick:"editInventoryProperties()"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refreshGroups()"},stream:{ngClick:"showGroupActivity()",awToolTip:"View Activity Stream",mode:"all"},help:{mode:"all",awToolTip:"Get help building your inventory",ngClick:"showGroupHelp()",id:"inventory-summary-help"}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",ngShow:"group.id > 1",awToolTip:"{{ group.status_tooltip }}",dataTipWatch:"group.launch_tooltip",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",ngShow:"group.id > 1",dataPlacement:"top",ngClick:"showHosts(group.id, group.group_id, group.show_failures)",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",dataTipWatch:"group.launch_tooltip",ngShow:"group.id > 1 && (group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate({{ group.id }})",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"group.id > 1 && (group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{mode:"all",ngClick:"editGroup({{ group.group_id + ',' + group.id }})",awToolTip:"Edit group",ngShow:"group.id > 1",dataPlacement:"top"},"delete":{mode:"all",ngClick:"deleteGroup({{ group.id + ',' + group.group_id }})",awToolTip:"Delete group",ngShow:"group.id != 1",dataPlacement:"top"}}}),angular.module("InventoryHostsDefinition",[]).value("InventoryHosts",{name:"hosts",iterator:"host",editTitle:"{{ selected_group }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,"class":"table-condensed table-no-border",fields:{name:{key:!0,label:"Hosts",ngClick:"editHost(host.id)",searchPlaceholder:"search_place_holder",columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",dataHostId:"{{ host.id }}",dataType:"host",awDraggable:"true"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"},"delete":{ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash",awToolTip:"Delete host",dataPlacement:"top"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createHost()",ngHide:"selected_tree_id == 1",awToolTip:"Create a new host"},stream:{ngClick:"showHostActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("JobEventsListDefinition",[]).value("JobEventList",{name:"jobevents",iterator:"jobevent",editTitle:"Job Events",index:!1,hover:!0,hasChildren:!0,filterBy:"{ show: true }",navigationLinks:{details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",active:!0,icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",icon:"icon-laptop"}},fields:{created:{label:"Created On",columnClass:"col-lg-1 col-md-1 hidden-sm hidden-xs",key:!0,nosort:!0,searchable:!1,link:!1},status:{label:"Status",showValue:!1,columnClass:"col-sm-1 col-xs-2 text-center",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}],nosort:!0,searchable:!1,ngClick:"viewJobEvent({{ jobevent.id }})",awToolTip:"{{ jobevent.statusBadgeToolTip }}",dataPlacement:"top",badgeIcon:"fa icon-job-{{ jobevent.status }}",badgePlacement:"left",badgeToolTip:"{{ jobevent.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgClick:"viewJobEvent({{ jobevent.id }})"},event_display:{label:"Event",hasChildren:!0,ngClick:"toggleChildren(jobevent.id, jobevent.related.children)",nosort:!0,searchable:!1,ngClass:"{{ jobevent.class }}",appendHTML:"jobevent.event_detail"},host:{label:"Host",ngBind:"jobevent.summary_fields.host.name",ngHref:"{{ jobevent.hostLink }}",searchField:"hosts__name",nosort:!0,searchOnly:!1,id:"job-event-host-header","class":"break",columnClass:"col-lg-2 hidden-sm hidden-xs"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{columnClass:"col-sm-1 col-xs-2",view:{label:"View",ngClick:"viewJobEvent(jobevent.id)",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("JobHostDefinition",[]).value("JobHostList",{name:"jobhosts",iterator:"jobhost",editTitle:"All summaries",index:!0,hover:!0,navigationLinks:{ngHide:"host_id !== null",details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",active:!0,icon:"icon-laptop"}},fields:{job:{label:"Job ID",ngClick:"showJob(jobhost.job)",columnShow:"host_id !== null",key:!0,desc:!0},host:{label:"Host",key:!0,sourceModel:"host",sourceField:"name",ngBind:"jobhost.host_name",ngHref:"jobhost.hostLinkTo"},status:{label:"Status",badgeNgHref:"{{ jobhost.statusLinkTo }}",badgeIcon:"fa icon-job-{{ jobhost.status }}",badgePlacement:"left",badgeToolTip:"{{ jobhost.statusBadgeToolTip }}",badgeTipPlacement:"top",ngHref:"{{ jobhost.statusLinkTo }}",awToolTip:"{{ jobhost.statusBadgeToolTip }}",dataPlacement:"top",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}]},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},ok:{label:"Success",searchable:!1},changed:{label:"Changed",searchable:!1},failures:{label:"Failure",searchable:!0,searchLabel:"Contains failed events?",searchType:"gtzero"},dark:{label:"Unreachable",searchable:!0,searchType:"gtzero",searchLabel:"Contains unreachable hosts?"},skipped:{label:"Skipped",searchable:!1}},actions:{help:{awPopOver:"
\n
Success
Tasks successfully executed on the host.
\n
Changed
Actions taken on the host.
\n
Failure
Tasks that failed on the host.
\n
Unreachable
Times the ansible server could not reach the host.
\n
Skipped
Tasks bypassed and not performed on the host due to prior task failure or the host being unreachable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Job Host Summary",id:"jobhost-help-button"},refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refresh()",ngShow:"host_id == null"}},fieldActions:{}}),angular.module("JobTemplatesListDefinition",[]).value("JobTemplateList",{name:"job_templates",iterator:"job_template",selectTitle:"Add Job Template",editTitle:"Job Templates",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addJobTemplate()",basePaths:["job_templates"],awToolTip:"Create a new template"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editJobTemplate(job_template.id)",icon:"icon-edit",awToolTip:"Edit template","class":"btn-default btn-xs",dataPlacement:"top"},submit:{label:"Launch",icon:"icon-rocket",mode:"all","class":"btn-xs btn-success",ngClick:"submitJob(job_template.id)",awToolTip:"Start a job using this template",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteJobTemplate(job_template.id, job_template.name)",icon:"icon-trash","class":"btn-danger btn-xs",awToolTip:"Delete template",dataPlacement:"top"}}}),angular.module("JobsListDefinition",[]).value("JobList",{name:"jobs",iterator:"job",editTitle:"Jobs",index:!1,hover:!0,"class":"jobs-table",fields:{id:{label:"Job ID",key:!0,desc:!0,searchType:"int"},inventory:{label:"Inventory ID",searchType:"int",searchOnly:!0},created:{label:"Create On",link:!1,searchable:!1},job_template:{label:"Job Template",ngBind:"job.summary_fields.job_template.name",ngHref:"{{ '/#/job_templates/' + job.job_template }}",sourceModel:"job_template",sourceField:"name"},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},status:{label:"Status","class":"job-{{ job.status }}",searchType:"select",linkTo:"{{ job.statusLinkTo }}",searchOptions:[{name:"new",value:"new"},{name:"waiting",value:"waiting"},{name:"pending",value:"pending"},{name:"running",value:"running"},{name:"successful",value:"successful"},{name:"error",value:"error"},{name:"failed",value:"failed"},{name:"canceled",value:"canceled"}],badgeIcon:"fa icon-job-{{ job.status }}",badgePlacement:"left",badgeToolTip:"{{ job.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgHref:"{{ job.statusLinkTo }}",awToolTip:"{{ job.statusBadgeToolTip }}",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{submit:{label:"Relaunch",icon:"icon-rocket",mode:"all",ngClick:"submitJob(job.id, job.summary_fields.job_template.name)",awToolTip:"Start the job",dataPlacement:"top"},cancel:{label:"Stop",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Cancel a running or pending job",ngShow:"job.status == 'pending' || job.status == 'running' || job.status == 'waiting'",dataPlacement:"top"},"delete":{label:"Delete",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Delete the job",ngShow:"job.status != 'pending' && job.status != 'running' && job.status != 'waiting'",dataPlacement:"top"},dropdown:{type:"DropDown",label:"View",icon:"fa-search-plus","class":"btn-default btn-xs",options:[{ngClick:"editJob(job.id, job.summary_fields.job_template.name)",label:"Status"},{ngClick:"viewEvents(job.id, job.summary_fields.job_template.name)",label:"Events",ngHide:"job.status == 'new'"},{ngClick:"viewSummary(job.id, job.summary_fields.job_template.name)",label:"Host Summary",ngHide:"job.status == 'new'"}]}}}),angular.module("OrganizationListDefinition",[]).value("OrganizationList",{name:"organizations",iterator:"organization",selectTitle:"Add Organizations",editTitle:"Organizations",hover:!0,index:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addOrganization()",awToolTip:"Create a new organization"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editOrganization(organization.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit organization",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteOrganization(organization.id, organization.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete organization",dataPlacement:"top"}}}),angular.module("PermissionListDefinition",[]).value("PermissionList",{name:"permissions",iterator:"permission",selectTitle:"Add Permission",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',editTitle:"Permissions",index:!0,well:!0,fields:{name:{key:!0,label:"Name",ngClick:"editPermission(permission.id)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},actions:{add:{mode:"all",ngClick:"addPermission()",awToolTip:"Add a new permission",ngShow:"PermissionAddAllowed"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editPermission(permission.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit permission",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deletePermission(permission.id, permission.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete permission",ngShow:"PermissionAddAllowed",dataPlacement:"top"}}}),angular.module("ProjectsListDefinition",[]).value("ProjectList",{name:"projects",iterator:"project",selectTitle:"Add Project",editTitle:"Projects",selectInstructions:"
Select existing projects by clicking each project or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new project by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",columnClass:"hidden-sm hidden-xs",excludeModal:!0},scm_type:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0},status:{label:"Status",ngClick:"showSCMStatus(project.id)",awToolTip:"View details of last SCM Update",dataPlacement:"top",badgeIcon:"{{ 'fa icon-failures-' + project.badge }}",badgePlacement:"left",searchType:"select",searchOptions:[],excludeModal:!0},last_updated:{label:"Last Updated",type:"date",excludeModal:!0,searchable:!1}},actions:{add:{mode:"all",ngClick:"addProject()",awToolTip:"Create a new project"},help:{awPopOver:"
\n
Updating
A source control update is in progress.
\n
Never Updated
This project has not yet been updated from source control.
\n
Failed
An error occurred during the most recent source control update, click the status text for more information.
\n
Successful
TThe latest source control update completed successfully.
\n
Missing
The previously configured local project directory is missing.
\n
N/A
The project is not linked to source control, so updates are not applicable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all",awToolTip:"Click for help",awTipPlacement:"top"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editProject(project.id)",awToolTip:"Edit project properties",dataPlacement:"top"},scm_update:{label:"Update",ngClick:"SCMUpdate(project.id)",awToolTip:"{{ project.scm_update_tooltip }}",ngClass:"project.scm_type_class",dataPlacement:"top"},cancel:{label:"Stop",ngClick:"cancelUpdate(project.id, project.name)",awToolTip:"Cancel a running SCM update process",ngShow:"project.status == 'updating'",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteProject(project.id, project.name)",awToolTip:"Permanently remove project from the database",ngShow:"project.status !== 'updating'",dataPlacement:"top"}}}),angular.module("StreamListDefinition",[]).value("StreamList",{name:"activities",iterator:"activity",editTitle:"Activity Stream",selectInstructions:"",index:!1,hover:!0,"class":"table-condensed",searchWidgets:3,fields:{timestamp:{label:"Event Time",key:!0,desc:!0,noLink:!0,searchable:!1},user:{label:"Initiated by",ngBindHtml:"activity.user",sourceModel:"actor",sourceField:"username",searchPlaceholder:"Username",searchWidget:1},description:{label:"Action",ngBindHtml:"activity.description",nosort:!0,searchable:!1,columnClass:"col-lg-7"},system_event:{label:"System event",searchOnly:!0,searchType:"isnull",sourceModel:"actor",sourceField:"username",searchWidget:1},all_objects:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All resources",searchWidget:2},credential_search:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Credential name",searchWidget:2,searchField:"object1"},group_search:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Group name",searchWidget:2,searchField:"object1"},host_search:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Host name",searchWidget:2,searchField:"object1"},inventory_search:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Inventory name",searchWidget:2,searchField:"object1"},job_template_search:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Job template name",searchWidget:2,searchField:"object1"},job_search:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:2,searchField:"object1"},organization_search:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Organization name",searchWidget:2,searchField:"object1"},project_search:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Project name",searchWidget:2,searchField:"object1"},user_search:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Primary username",searchWidget:2,searchField:"object1"},all_objects3:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All related resources",searchWidget:3,searchField:"object2"},credential_search3:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Related credential name",searchWidget:3,searchField:"object2"},group_search3:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Related group name",searchWidget:3,searchField:"object2"},host_search3:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Related host name",searchWidget:3,searchField:"object2"},inventory_search3:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Related inventory name",searchWidget:3,searchField:"object2"},job_search3:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:3,searchField:"object2"},job_template_search3:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Related job template name",searchWidget:3,searchField:"object2"},organization_search3:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Related organization name",searchWidget:3,searchField:"object2"},project_search3:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Related project name",searchWidget:3,searchField:"object2"},user_search3:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Related username",searchWidget:3,searchField:"object2"}},actions:{refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refreshStream()"},close:{mode:"all",awToolTip:"Close Activity Stream view",ngClick:"closeStream()"}},fieldActions:{view:{label:"View",ngClick:"showDetail(activity.id)",icon:"fa-zoom-in","class":"btn-default btn-xs",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("TeamsListDefinition",[]).value("TeamList",{name:"teams",iterator:"team",selectTitle:"Add Team",editTitle:"Teams",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"},organization:{label:"Organization",ngBind:"team.organization_name",sourceModel:"organization",sourceField:"name"}},actions:{add:{mode:"all",ngClick:"addTeam()",awToolTip:"Create a new team"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editTeam(team.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit team",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteTeam(team.id, team.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete team",dataPlacement:"top"}}}),angular.module("UserListDefinition",[]).value("UserList",{name:"users",iterator:"user",selectTitle:"Add Users",editTitle:"Users",selectInstructions:"
Select existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.
When available, a brand new user can be created by clicking the green Create New button.
",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{add:{label:"Create New",mode:"all",ngClick:"addUser()",basePaths:["organizations","users"],"class":"btn-xs",awToolTip:"Create a new user"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editUser(user.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit user",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteUser(user.id, user.username)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete user",dataPlacement:"top"}}}),angular.module("InventorySyncStatusWidget",["RestServices","Utilities"]).factory("InventorySyncStatus",["$rootScope","$compile",function(a,b){return function(a){function c(a){var b=a.label,c=a.count,d=a.fail,e=a.link,f=a.fail_link,g="
\n",d+="\n",d+="\n",d+=c({label:"Inventories",count:k.inventories&&k.inventories.total_with_inventory_source?k.inventories.total_with_inventory_source:0,fail:k.inventories&&k.inventories.inventory_failed?k.inventories.inventory_failed:0,link:"/#/inventories/?has_inventory_sources=true",fail_link:"/#/inventories/?inventory_sources_with_failures=true"}),e=0,f=0,k.inventory_sources)for(h in k.inventory_sources)e+=k.inventory_sources[h].total?k.inventory_sources[h].total:0,f+=k.inventory_sources[h].failed?k.inventory_sources[h].failed:0;d+=c({label:"Groups",count:e,fail:f,link:"/#/home/groups/?has_external_source=true",fail_link:"/#/home/groups/?status=failed"});for(h in k.inventory_sources)k.inventory_sources[h].total&&(d+=c({label:k.inventory_sources[h].label,count:k.inventory_sources[h].total?k.inventory_sources[h].total:0,fail:k.inventory_sources[h].failed?k.inventory_sources[h].failed:0,link:"/#/home/groups/?source="+h,fail_link:"/#/home/groups/?status=failed&source="+h}));d+="\n",d+="
\n",e+="\n",e+="\n",f=0,l.scm_types)for(h in l.scm_types)f+=l.scm_types[h].total?l.scm_types[h].total:0;e+=c({label:"Projects",link:"/#/projects",count:f,fail:l.projects&&l.projects.failed?l.projects.failed:0,fail_link:"/#/projects/?status=failed"}),i=[];for(h in l.scm_types)i.push(h);for(i.sort(),d=0;d\n",e+="
\n",e+="
\n",e+="
\n",e+="\n",g=angular.element(document.getElementById(k)),g.html(e),b(g)(j),j.$emit("WidgetLoaded")}}]),angular.module("StreamWidget",["RestServices","Utilities","StreamListDefinition","SearchHelper","PaginationHelpers","RefreshHelper","ListGenerator","StreamWidget","AuthService"]).factory("setStreamHeight",[function(){return function(){var a=$("#stream-content").height(),b=parseInt($("#tab-content-container").css("min-height").replace(/px/,"")),c=a>b?a:b;$("#tab-content-container").css({"min-height":c})}}]).factory("ShowStream",["setStreamHeight","Authorization",function(a){return function(){var b=$("#stream-container");b.css({position:"absolute",top:0,left:0,width:"100%","min-height":"100%","background-color":"#FFF"}),a(),b.show("slide",{direction:"left"},{duration:500,queue:!1})}}]).factory("HideStream",["LoadBreadCrumbs",function(a){return function(){var b=$("#stream-container");b.hide("slide",{direction:"left"},{duration:500,queue:!1}),setTimeout(function(){b.detach(),b.empty(),b.unbind(),$("#tab-content-container").css({"min-height":0})},500),a()}}]).factory("StreamBreadCrumbs",["$rootScope","$location",function(a,b){return function(){a.breadcrumbs=[];var c,d,e,f,g=b.path().split("/");for(g.splice(0,1),e=0;e=f;f++)c+="/"+g[f];for(f=0;f0)for(f=0;e>=f;f++)c+="/"+g[f];else c="/"+g[e];d=g[e],d=d.charAt(0).toUpperCase()+d.slice(1)}a.breadcrumbs.push({path:c,title:d,ngClick:"closeStream('"+c+"')"})}}}]).factory("FixUrl",[function(){return function(a){return a.replace(/\/api\/v1\//,"/#/")}}]).factory("BuildUrl",[function(){return function(a){var b="/#/";switch(a.base){case"group":case"host":b+="home/"+a.base+"s/?id="+a.id;break;case"inventory":b+="inventories/"+a.id+"/";break;default:b+=a.base+"s/"+a.id+"/"}return b}}]).factory("BuildDescription",["FixUrl","BuildUrl",function(a,b){return function(a){function c(a){return a.replace(/^_deleted_\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d+\+\d+:\d+_/,"")}var d,e,f,g,h,i,j,k;d=a.operation,d+=/e$/.test(a.operation)?"d ":"ed ",e=d,f=a.object1,g=a.object2,h=a.summary_fields[f]?a.summary_fields[f][0]:null,i=f===g?a.summary_fields[f][1]:a.summary_fields[g]?a.summary_fields[g][0]:null,("user"===f||"user"===g)&&(a.summary_fields.user[0].name=a.summary_fields.user[0].username),i&&i.name&&!/^_delete/.test(i.name)?(i.base=g,d+=g+' '+i.name+""+("disassociate"===a.operation?" from ":" to "),e+=g+" "+i.name+("disassociate"===a.operation?" from ":" to ")):g&&(j="",i&&i.name&&(j=" "+c(i.name)),d+=g+j+("disassociate"===a.operation?" from ":" to "),e+=g+j+("disassociate"===a.operation?" from ":" to ")),h&&h.name&&!/^\_delete/.test(h.name)?(h.base=f,d+=f+' '+h.name+"",e+=f+" "+h.name):f&&(j="",k="",!h||!h.name||h&&h.name&&/^_delete/.test(h.name)?a.changes&&a.changes.name?"string"==typeof a.changes.name?(j=" "+a.changes.name,k=j):"object"==typeof a.changes.name&&Array.isArray(a.changes.name)&&(j=" "+a.changes.name[0],k=j):"job"===f&&h&&a.changes&&a.changes.job_template?"delete"!==a.operation?(h.base=f,j=' '+h.id+" "+a.changes.job_template+"",k=" "+h.id+" "+a.changes.job_template):(j=" "+h.id+" "+a.changes.job_template,k=j):"job"===f&&h&&("delete"!==a.operation?(h.base=f,j=' '+h.id+"",k=" "+h.id):(j=" "+h.id,k=j)):h&&h.name&&(j=" "+c(h.name),k=j),d+=f+j,e+=f+k),a.description=d,a.description_nolink=e}}]).factory("ShowDetail",["$rootScope","Rest","Alert","GenerateForm","ProcessErrors","GetBasePath","FormatDate","ActivityDetailForm","Empty","Find",function(a,b,c,d,e,f,g,h,i,j){return function(a){var b,c,e,f=a.activity_id,i=a.scope,k=d,l=h,m=j({list:i.activities,key:"id",val:f});m&&(m.changes_stringified=JSON.stringify(m.changes,null," "),b=m.changes_stringified.match(/\n/g),c=b?b.length:1,c=1>c?3:10,l.fields.changes.rows=10,e=k.inject(l,{mode:"edit",modal:!0,related:!1}),e.changes=m.changes_stringified,e.user=(m.summary_fields.actor?m.summary_fields.actor.username:"system")+" on "+g(new Date(m.timestamps)),e.operation=m.description_nolink,e.formModalAction=function(){$("#form-modal").modal("hide")},$("#form-modal").on("show.bs.modal",function(){$("#form-modal-body").css({width:"auto",height:"auto","max-height":"100%"})}),e.formModalActionLabel="OK",e.formModalCancelShow=!1,e.formModalInfo=!1,e.formModalHeader="Event "+m.id,e.$$phase||e.$digest())}}]).factory("Stream",["$rootScope","$location","Rest","GetBasePath","ProcessErrors","Wait","StreamList","SearchInit","PaginateInit","GenerateList","FormatDate","ShowStream","HideStream","BuildDescription","FixUrl","BuildUrl","ShowDetail","StreamBreadCrumbs","setStreamHeight","Find","Store",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){return function(c){var e,f,o,v,w=g,x=d("activity_stream"),y=j,z=b.path().replace(/^\//,"").split("/")[0],A=c.scope,B=u("CurrentSearchParams"),C=c&&c.inventory_name?c.inventory_name:null,D=c&&c.url?c.url:null;a.flashMessage=null,D?x=D:"/home"!==b.path()&&(e="inventories"===z?"inventory":z.replace(/s$/,""),f=b.path().split("/"),f.splice(0,1),f.length>1&&/^\d+/.test(f[f.length-1])?(e=f[f.length-2],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?"+e+"__id="+f[f.length-1]):f.length>1?(e=f[f.length-1],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?or__object1="+e+"&or__object2="+e):x+="?or__object1="+e+"&or__object2="+e),$("#tab-content-container").append('
'),r(),C&&(o=t({list:a.breadcrumbs,key:"title",val:"{{ inventory_name }}"}),o&&(o.title=C)),l(),v=y.inject(w,{mode:"edit",id:"stream-content",searchSize:"col-lg-3",secondWidget:!0,activityStream:!0}),v.streamTitle=c&&c.title?c.title:null,v.closeStream=function(a){m(),v.searchCleanup&&v.searchCleanup(),B&&h({scope:A,set:B.set,list:B.list,url:B.defaultUrl,iterator:B.iterator,sort_order:B.sort_order,setWidgets:!1}),a&&b.path(a)},v.refreshStream=function(){v.search(w.iterator)},v.showDetail=function(a){q({scope:v,activity_id:a})},v.removeStreamPostRefresh&&v.removeStreamPostRefresh(),v.removeStreamPostRefresh=v.$on("PostRefresh",function(){var a,b,c,d,e,f;for(a=0;a'+v.activities[a].summary_fields.actor.username+"":"system",d=/^\_delete/,e=v.activities[a].object1,f=v.activities[a].object2,e&&v.activities[a].summary_fields[e]&&v.activities[a].summary_fields[e].name?d.test(v.activities[a].summary_fields[e].name)?v.activities[a].objects=v.activities[a].summary_fields[e].name:(c=p(v.activities[a].summary_fields.object1),v.activities[a].objects=''+v.activities[a].summary_fields[e].name+""):v.activities[a].object1&&(v.activities[a].objects=v.activities[a].object1),f&&v.activities[a].summary_fields[f]&&v.activities[a].summary_fields[f].name?d.test(v.activities[a].summary_fields.object2.name)?v.activities[a].objects+=","+v.activities[a].summary_fields[f].name:(c=p(v.activities[a].summary_fields.object2),v.activities[a].objects+=', '+v.activities[a].summary_fields[f].name+""):v.activities[a].object2&&(v.activities[a].objects+=", "+v.activities[a].object2),n(v.activities[a]);setTimeout(function(){s()},500)}),h({scope:v,set:w.name,list:w,url:x}),i({scope:v,list:w,url:x}),v.search(w.iterator)}}]),angular.module("AuthService",["ngCookies","Utilities"]).factory("Authorization",["$http","$rootScope","$location","$cookieStore","GetBasePath",function(a,b,c,d,e){return{setToken:function(a,c){d.remove("token"),d.remove("token_expires"),d.remove("userLoggedIn"),d.put("token",a),d.put("token_expires",c),d.put("userLoggedIn",!0),d.put("sessionExpired",!1),b.token=a,b.userLoggedIn=!0,b.token_expires=c,b.sessionExpired=!1},isUserLoggedIn:function(){return void 0===b.userLoggedIn&&(b.userLoggedIn=d.get("userLoggedIn"),b.sessionExpired=d.get("sessionExpired")),b.userLoggedIn},getToken:function(){return b.token?b.token:d.get("token")},retrieveToken:function(b,c){return a({method:"POST",url:e("authtoken"),data:{username:b,password:c}})},logout:function(){var a=angular.element(document.getElementById("main-view")).scope();a.$destroy(),b.$destroy(),d.remove("accordions"),d.remove("token"),d.remove("token_expires"),d.remove("current_user"),d.remove("lastPath"),d.put("userLoggedIn",!1),d.put("sessionExpired",!1),d.remove("lastPath","/home"),b.current_user={},b.license_tested=void 0,b.userLoggedIn=!1,b.sessionExpired=!1,b.token=null,b.token_expires=null,b.lastPath="/home"},getLicense:function(){return a({method:"GET",url:e("config"),headers:{Authorization:"Token "+this.getToken()}})},setLicense:function(a){a.tested=!1,d.put("license",a)},licenseTested:function(){var a,c;return void 0!==b.license_tested?c=b.license_tested:(a=d.get("license"),c=a&&void 0!==a.tested?a.tested:!1),c},getUser:function(){return a({method:"GET",url:"/api/v1/me/",headers:{Authorization:"Token "+this.getToken()}})},setUserInfo:function(a){b.current_user=a.results[0],d.put("current_user",a.results[0])},restoreUserInfo:function(){b.current_user=d.get("current_user")},getUserInfo:function(a){var c;return b.current_user?b.current_user[a]:(this.restoreUserInfo(),c=d.get("current_user"),c[a])}}}]),angular.module("InventoryTree",["Utilities","RestServices","GroupsHelper","PromptDialog"]).factory("SortNodes",[function(){return function(a){var b,c,d=[],e=[];for(b=0;b0?!0:!1,has_inventory_sources:s[e].has_inventory_sources,id:r,source:s[e].summary_fields.inventory_source.source,group_id:s[e].id,event_level:c,children:i,ngicon:s[e].children.length>0?"fa fa-minus-square-o node-toggle":"fa fa-square-o node-no-toggle",ngclick:"toggle("+r+")",related:{children:s[e].children.length>0?s[e].related.children:"",inventory_source:s[e].related.inventory_source},status:s[e].summary_fields.inventory_source.status,status_class:k["class"],status_tooltip:k.tooltip,launch_tooltip:k.launch_tip,launch_class:k.launch_class,hosts_status_tip:n.tooltip,show_failures:n.failures,hosts_status_class:n["class"],selected_class:"",show:!0,isDraggable:!0,isDroppable:!0},q.push(o),p&&o.group_id===p&&(m.selected_tree_id=r,m.selected_group_id=o.group_id),s[e].children.length>0&&j(s[e].children,r,c+1)}}function k(){e("start"),a.setUrl(b("inventory")+l+"/"),a.get().success(function(a){m.$emit("buildAllGroups",a.name,a.related.tree,a.related.groups)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+l+". GET returned: "+b})})}var l=h.inventory_id,m=h.scope,n=h.refresh,o=h.emit,p=h.new_group_id,q=[],r=1;m.buildAllGroupsRemove&&m.buildAllGroupsRemove(),m.buildAllGroupsRemove=m.$on("buildAllGroups",function(b,d,f){a.setUrl(f),a.get().success(function(a){i(a),j(a,0,0),m.autoShowGroupHelp=0===a.length?!0:!1,n?(m.groups=q,m.$emit("GroupTreeRefreshed",d,q,o)):m.$emit("GroupTreeLoaded",d,q,o)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory tree for: "+l+". GET returned: "+b})})}),k()}}]).factory("UpdateGroup",["ApplyEllipsis","GetSyncStatusMsg","Empty",function(a,b,c){return function(d){var e,f,g,h,i,j=d.scope,k=d.group_id,l=d.properties;for(e=0;e\n',m+='
\n',m+='
\n',m+='
\n',m+='\n',m+=1===k.id||0===l.parent?"
Move Group
\n":"
Copy or Move?
\n",m+="
\n",m+='
\n',1===k.id?m+="
Are you sure you want to move group "+l.name+" to the top level?
":0===l.parent?m+="
Are you sure you want to move group "+l.name+" from the top level and make it a child of "+k.name+"?
":(m+='
\n',m+="
Would you like to copy or move group "+l.name+" to group "+k.name+"?
\n",m+="\n",i=angular.element(document.getElementById("inventory-modal-container")),i.empty().append(m),a(i)(j),$("#copy-prompt-modal").modal({backdrop:"static",keyboard:!0,show:!0}),j.moveGroup=function(){var a,b,i;$("#copy-prompt-modal").modal("hide"),e("start"),j.removeGroupRemove&&j.removeGroupRemove(),j.removeGroupRemove=j.$on("removeGroup",function(){l.parent>0?(i=d({list:j.groups,key:"id",val:l.parent}),a=h("base")+"groups/"+i.group_id+"/children/",f.setUrl(a),f.post({id:l.group_id,disassociate:1}).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to remove "+l.name+" from "+i.name+". POST returned status: "+b})})):j.$emit("GroupDeleteCompleted")}),a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id},f.setUrl(a),f.post(b).success(function(){j.$emit("removeGroup")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})},j.copyGroup=function(){$("#copy-prompt-modal").modal("hide"),e("start");var a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id};f.setUrl(a),f.post(b).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})}}}]).factory("CopyMoveHost",["$compile","Alert","ProcessErrors","Find","Wait","Rest","Empty","GetBasePath",function(a,b,c,d,e,f,g,h){return function(b){var g,i,j=b.scope,k=d({list:j.groups,key:"id",val:b.target_tree_id}),l=d({list:j.hosts,key:"id",val:b.host_id}),m=!1,n="";if(l.summary_fields.all_groups)for(i=0;i\n',n+='
URL must begin with ssh, http or https and may not contain '@'
\n"),p+='\n',b.chkPass&&(p+='
Password must be stronger
\n',p+='
\n',p+='
\n',p+='\n',p+="
\n",p+=k({hdr:"Password Complexity",content:'
A password with reasonable strength is required. As you type the password a progress bar will measure the strength. Sufficient strength is reached when the bar turns green.
Password strength is judged using the following:
Minimum 8 characters in length
\n
Contains a sufficient combination of the following items:\n
\n';for(b in this.form.actions)("all"===this.form.actions[b].mode||this.form.actions[b].mode===a.mode)&&(c+=this.button({btn:this.form.actions[b],action:b,toolbar:!0}));return c+="
\n");for(d in this.form.buttons)"object"==typeof this.form.buttons[d]&&(e=this.form.buttons[d],"save"===d&&(e.label="Save",e["class"]="btn-success"),"reset"===d&&(e.label="Reset",e["class"]="btn-default"),p+='\n");p+="
\n"),j=1,k=m.related[g].base?m.related[g].base:g,k=k.replace(/^\//,"");for(d in m.related[g].fields)j++,n+=i({list:m.related[g],fld:d,options:a,base:k});n+='
\n';for(b in f.fields)void 0!==f.fields[b].searchable&&f.fields[b].searchable!==!0||(void 0!==f.fields[b].searchWidget&&1!==f.fields[b].searchWidget||1!==c)&&f.fields[b].searchWidget!==c||(h+='
\n';
+for(j in t.actions)("all"===t.actions[j].mode||t.actions[j].mode===b.mode)&&(void 0===t.actions[j].basePaths||t.actions[j].basePaths&&t.actions[j].basePaths.indexOf(c)>-1)&&(s+=this.button({btn:t.actions[j],action:j,toolbar:!0}));"select"===b.mode&&t.selectInstructions&&(k={awPopOver:t.selectInstructions,dataPlacement:"top",dataContainer:"body","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Help",iconSize:"fa-lg"},s+=this.button({btn:k,action:"help",toolbar:!0})),s+="
\n');for(n in t.fields)void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+='
\n"),o=2,c=t.base?t.base:t.name,c=c.replace(/^\//,"");for(n in t.fields)o++,void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+=h({list:t,fld:n,options:b,base:c}));if("select"===b.mode||"lookup"===b.mode)s+='
\n"),"groups"!==t.name&&(s+=e("lookup"===b.mode||b.id&&"form-modal-body"===b.id?{set:t.name,iterator:t.iterator}:{set:t.name,iterator:t.iterator})),s}}}]),angular.module("PromptDialog",["Utilities"]).factory("Prompt",[function(){return function(a){var b,c=angular.element(document.getElementById("prompt-modal")),d=c.scope();d.promptHeader=a.hdr,d.promptBody=a.body,d.promptAction=a.action,b=null===a["class"]||void 0===a["class"]?"btn-danger":a["class"],$("#prompt_action_btn").removeClass(b).addClass(b),$(c).modal({backdrop:"static",keyboard:!0,show:!0})}}]),String.prototype.strReverse=function(){var a,b="";for(a=0;aA credential must be associated with either a user or a team. Choosing a user allows only the selected user access to the credential. Choosing a team shares the credential with all team members.",dataTitle:"Owner",dataPlacement:"right",dataContainer:"body"},user:{label:"User that owns this credential",type:"lookup",sourceModel:"user",sourceField:"username",ngClick:"lookUpUser()",ngShow:"owner == 'user'",awRequiredWhen:{variable:"user_required",init:"false"}},team:{label:"Team that owns this credential",type:"lookup",sourceModel:"team",sourceField:"name",ngClick:"lookUpTeam()",ngShow:"owner == 'team'",awRequiredWhen:{variable:"team_required",init:"false"}},kind:{label:"Type",excludeModal:!0,type:"select",ngOptions:"kind.label for kind in credential_kind_options",ngChange:"kindChange()",addRequired:!0,editRequired:!0,helpCollapse:[{hdr:"Select a Credential Type",content:"
\n
AWS
\n
Access keys for Amazon Web Services used for inventory management or deployment.
\n
Machine
\n
Authentication for remote machine access. This can include SSH keys, usernames, passwords, and sudo information. Machine credentials are used when submitting jobs to run playbooks against remote hosts.
Rackspace
\n
Access information for Rackspace Cloud used for inventory management or deployment.
\n
SCM
\n
Used to check out and synchronize playbook repositories with a remote source control management system such as Git, Subversion (svn), or Mercurial (hg). These credentials are used on the Projects tab.
Click on the regions field to see a list of regions for your cloud provider. You can select multiple regions, or choose All to include all regions. Tower will only be updated with Hosts associated with the selected regions.
Override variables found in ec2.ini and used by the inventory update script. For a detailed description of these variables view ec2.ini in the Ansible github repo.
Enter variables using either JSON or YAML syntax. Use the radio button to toggle between the two.
If checked, all variables for child groups and hosts will be removed and replaced by those found on the external source.
When not checked a merge will be performed, combining local variables with those found on the external source.
",dataTitle:"Overwrite Variables",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"update_on_launch",label:"Update on Launch",type:"checkbox",ngShow:"source.value !== '' && source.value !== null",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this inventory, refresh the inventory from the selected source before executing job tasks.
",dataTitle:"Update on Launch",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{labelClass:"col-lg-3",controlClass:"col-lg-5",save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("HostGroupsFormDefinition",[]).value("HostGroupsForm",{editTitle:"Host Groups",name:"host",well:!1,formLabelSize:"col-lg-3",formFieldSize:"col-lg-9",fields:{groups:{label:"Groups",type:"select",multiple:!0,ngOptions:"group.name for group in inventory_groups",addRequired:!0,editRequired:!0,awPopOver:"
Provide a host name, ip address, or ip address:port. Examples include:
',dataTitle:"Inventory Variables",dataPlacement:"right",dataContainer:"body"}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("JobEventDataDefinition",[]).value("JobEventDataForm",{editTitle:"{{ id }} - {{ event_display }}",name:"job_events",well:!1,"class":"horizontal-narrow",fields:{event_data:{label:!1,type:"textarea",readonly:!0,rows:18,"class":"modal-input-xxlarge"}}}),angular.module("JobEventsFormDefinition",[]).value("JobEventsForm",{name:"job_events",well:!1,forceListeners:!0,fields:{status:{labelClass:"job-{{ status }}",type:"custom",section:"Event",control:'
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",awRequiredWhen:{variable:"playbookrequired",init:"true"},column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
The number of parallel or simultaneous processes to use while executing the playbook. 0 signifies the default value from the ansible configuration file.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
',dataTitle:"Limit",dataPlacement:"right",dataContainer:"body"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting the Tower server using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",addRequired:!0,editRequired:!0,column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
For more information and examples see the Selecting Targets section under Inventory and Patterns in the Ansible documentation.
',dataContainer:"body",dataTitle:"Limit",dataPlacement:"right"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting Tower using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
A project must have at least one organization. Pick one organization now to create the project, and then after the project is created you can add additional organizations.
Only super users and organization administrators are allowed to make changes to projects. Associating one or more organizations to a project determins which organizations admins have access to modify the project.",dataTitle:"Organization",dataContainer:"body",dataPlacement:"right"},scm_type:{label:"SCM Type",type:"select",ngOptions:"type.label for type in scm_type_options",ngChange:"scmChange()",addRequired:!0,editRequired:!0},missing_path_alert:{type:"alertblock","class":"alert-info",ngShow:"showMissingPlaybooksAlert && scm_type.value == ''",alertTxt:'
WARNING: There are no unassigned playbook directories in the base project path {{ base_dir }}. Either the projects directory is empty, or all of the contents are already assigned to other projects. New projects can be checked out from source control by changing the SCM type option rather than specifying checkout paths manually. To continue with manual setup, log into the Tower host and ensure content is present in a subdirectory under {{ base_dir }}. Run "chown -R awx" on the content directory to ensure Tower can read the playbooks.
',closeable:!1},base_dir:{label:"Project Base Path",type:"textarea",showonly:!0,ngShow:"scm_type.value == ''",awPopOver:"
Base path used for locating playbooks. Directories found inside this path will be listed in the playbook directory drop-down. Together the base path and selected playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
",dataTitle:"Project Base Path",dataContainer:"body",dataPlacement:"right"},local_path:{label:"Playbook Directory",type:"select",id:"local-path-select",ngOptions:"path.label for path in project_local_paths",awRequiredWhen:{variable:"pathRequired",init:!1},ngShow:"scm_type.value == '' && !showMissingPlaybooksAlert",awPopOver:"
Select from the list of directories found in the base path.Together the base path and the playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
Note: If using SSH protocol for GitHub or Bitbucket, enter in the SSH key only, do not enter a username (other than git). Additionally, GitHub and Bitbucket do not support password authentication when using SSH protocol. GIT read only protocol (git://) does not use username or password information.',show:"scm_type.value == 'git'"},{hdr:"SVN URLs",content:'
Note: Mercurial does not support password authentication for SSH. If applicable, add the username, password and key below. Do not put the username and key in the URL. If using Bitbucket and SSH, do not supply your Bitbucket username.',show:"scm_type.value == 'hg'"}]},scm_branch:{labelBind:"scmBranchLabel",type:"text",ngShow:"scm_type && scm_type.value !== ''",addRequired:!1,editRequired:!1},credential:{label:"SCM Credential",type:"lookup",ngShow:"scm_type && scm_type.value !== ''",sourceModel:"credential",sourceField:"name",ngClick:"lookUpCredential()",addRequired:!1,editRequired:!1},checkbox_group:{label:"SCM Update Options",type:"checkbox_group",ngShow:"scm_type && scm_type.value !== ''",fields:[{name:"scm_clean",label:"Clean",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Remove any local modifications prior to performing an update.
",dataTitle:"SCM Clean",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_delete_on_update",label:"Delete on Update",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Delete the local repository in its entirety prior to performing an update.
Depending on the size of the repository this may significantly increase the amount of time required to complete an update.
",dataTitle:"SCM Delete",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_update_on_launch",label:"Update on Launch",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this project, perform an update to the local repository prior to starting the job.
",dataTitle:"SCM Update",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{add:{ngClick:"add('organizations')",icon:"icon-plus",label:"Add",awToolTip:"Add an organization"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('organizations', organization.id, organization.name)",icon:"icon-edit",awToolTip:"Edit the organization","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('organizations', organization.id, organization.name, 'organizations')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the organization"}}}}}),angular.module("TeamFormDefinition",[]).value("TeamForm",{addTitle:"Create Team",editTitle:"{{ name }}",name:"team",well:!0,collapse:!0,collapseTitle:"Team Settings",collapseMode:"edit",collapseOpen:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{name:{label:"Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!1},description:{label:"Description",type:"text",addRequired:!1,editRequired:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",awRequiredWhen:{variable:"teamrequired",init:"true"}}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",add:"Add a new credential"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Modify the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{add:{ngClick:"add('projects')",icon:"icon-plus",label:"Add"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('projects', project.id, project.name)",icon:"icon-edit",awToolTip:"Modify the project","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('projects', project.id, project.name, 'projects')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the project"}}},users:{type:"collection",title:"Users",iterator:"user",open:!1,actions:{add:{ngClick:"add('users')",icon:"icon-plus",label:"Add",awToolTip:"Add a user"}},fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('users', user.id, user.username)",icon:"icon-edit",awToolTip:"Edit user","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('users', user.id, user.username, 'users')",icon:"icon-terash","class":"btn-danger",awToolTip:"Remove user"}}}}}),angular.module("UserFormDefinition",[]).value("UserForm",{addTitle:"Create User",editTitle:"{{ username }}",name:"user",well:!0,forceListeners:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{first_name:{label:"First Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},last_name:{label:"Last Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},email:{label:"Email",type:"email",addRequired:!0,editRequired:!0,autocomplete:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",excludeMode:"edit",awRequiredWhen:{variable:"orgrequired",init:!0}},username:{label:"Username",type:"text",awRequiredWhen:{variable:"not_ldap_user",init:!0},autocomplete:!1},password:{label:"Password",type:"password",ngShow:"ldap_user == false",addRequired:!0,editRequired:!1,ngChange:"clearPWConfirm('password_confirm')",autocomplete:!1,chkPass:!0},password_confirm:{label:"Confirm Password",type:"password",ngShow:"ldap_user == false",addRequired:!1,editRequired:!1,awPassMatch:!0,associated:"password",autocomplete:!1},is_superuser:{label:"Superuser (User has full system administration privileges.)",type:"checkbox",trueValue:"true",falseValue:"false","default":"false",ngShow:"current_user['is_superuser'] == true"},ldap_user:{label:"Created by LDAP",type:"checkbox",readonly:!0}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",awToolTip:"Add a credential for this user"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Edit the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},admin_of_organizations:{type:"collection",title:"Admin of Organizations",iterator:"adminof",open:!1,base:"/organizations",actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},teams:{type:"collection",title:"Teams",iterator:"team",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}}}}),angular.module("InventoryGroupsHelpDefinition",[]).value("InventoryGroupsHelp",{story:{hdr:"Building your inventory",width:510,height:560,steps:[{intro:"Start by creating a group:",img:{src:"groups001.png",maxWidth:338,maxHeight:222},box:'Click on the groups list (the left side of the page) to add a new group.',autoOffNotice:!0},{intro:"Enter group properties:",img:{src:"groups002.png",maxWidth:443,maxHeight:251},box:'Enter the group name, a description and any inventory variables. Variables can be entered using either JSON or YAML syntax. For more on inventory variables, see docs.ansible.com/intro_inventory.html'},{intro:"Cloud inventory: select cloud source",img:{src:"groups003.png",maxWidth:412,maxHeight:215},box:'For a cloud inventory, choose the cloud provider from the list and select your credentials. If you have not already setup credentials for the provider, you will need to do that first on the Credentials tab.'},{intro:"Cloud inventory: synchronize Tower with the cloud",img:{src:"groups004.png",maxWidth:261,maxHeight:221},box:'To pull the cloud inventory into Tower, initiate an inventory sync by clicking .'},{intro:"Groups can have subgroups:",img:{src:"groups005.png",maxWidth:430,maxHeight:206},box:'
First, select a group. Then click to create a new group. The new group will be added to the selected group.
'},{intro:"Copy or move groups:",img:{src:"groups006.png",maxWidth:263,maxHeight:211},box:'
Copy or move a group by dragging and dropping its name onto another group name. A dialog will appear asking if the group should be coppied or moved.
Your Ansible Tower license has reached capacity for the number of managed hosts allowed. You will not be able to add any additional hosts.
"+i,c(d,f,g,null,!0)))}}]),angular.module("ChildrenHelper",["RestServices","Utilities"]).factory("ToggleChildren",[function(){return function(a){function b(a){var b;for(i[a].ngicon="fa fa-minus-square-o node-toggle",b=a+1;b10?10:i,i=3>i?3:i,f.fields[h].rows=i);break;case"results":if(a.event_data&&a.event_data.res&&void 0===a.event_data.res[h])delete f.fields[h];else if(Array.isArray(a.event_data.res[h])&&0!==a.event_data.res[h].length){for(j="",c=0;c10?10:i,i=3>i?3:i,f.fields[h].rows=i)}else delete f.fields[h];break;case"module_name":case"module_args":a.event_data&&a.event_data.res&&(void 0===a.event_data.res.invocation||void 0===a.event_data.res.invocation[h])&&delete f.fields[h]}b=d.inject(f,{mode:"edit",modal:!0,related:!1}),d.reset(),b.formModalAction=function(){$("#form-modal").modal("hide")},b.formModalActionLabel="OK",b.formModalCancelShow=!1,b.formModalInfo="View JSON",$("#form-modal .btn-success").removeClass("btn-success").addClass("btn-none"),$("#form-modal").addClass("skinny-modal"),b.formModalHeader=a.event_display.replace(/^\u00a0*/g,""),b.formModalInfoAction=function(){var b=g,c=b.inject(l,{mode:"edit",modal:!0,related:!1,modal_selector:"#form-modal2",modal_body_id:"form-modal2-body",modal_title_id:"formModal2Header"});b.reset(),c.formModal2Header=a.event_display.replace(/^\u00a0*/g,""),c.event_data=JSON.stringify(a.event_data,null," "),c.formModal2ActionLabel="OK",c.formModal2CancelShow=!1,c.formModal2Info=!1,c.formModalInfo="View JSON",c.formModal2Action=function(){$("#form-modal2").modal("hide")},$("#form-modal2 .btn-success").removeClass("btn-success").addClass("btn-none")},"string"==typeof a.event_data.res&&(b.traceback=a.event_data.res);for(h in f.fields)switch(h){case"status":b.status=a.failed?"error":a.changed?"changed":"success";break;case"created":n=new Date(a.created),b.created=k(n);break;case"host":a.summary_fields&&a.summary_fields.host&&(b.host=a.summary_fields.host.name);break;case"id":case"task":case"play":b[h]=a[h];break;case"start":case"end":a.event_data&&a.event_data.res&&!m(a.event_data.res[h])&&(b[h]=a.event_data.res[h]);break;case"results":if(Array.isArray(a.event_data.res[h])&&a.event_data.res[h].length>0){for(j="",c=0;c button.',"alert-info"):(f("start"),a.setUrl(l.related.inventory_source),a.get().success(function(a){var b=a.related.current_update?a.related.current_update:a.related.last_update;d({group_name:a.summary_fields.group.name,last_update:b,license_error:a.summary_fields.last_update&&a.summary_fields.last_update.license_error?!0:!1,tree_id:j,group_id:k,parent_scope:i})}).error(function(a,c){f("stop"),b(i,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+l.related.inventory_source+" POST returned status: "+c})})))}}]).factory("GetHostsStatusMsg",[function(){return function(a){var b,c,d,e=a.active_failures,f=a.total_hosts;return e>0?(b=f+(1===f?" host":" hosts")+". "+e+" with failed jobs.",d="true",c=!0):(c=!1,0===f?(b="Group contains 0 hosts.",d="na"):(b=f+(1===f?" host":" hosts")+". No job failures",d="false")),{tooltip:b,failures:c,"class":d}}}]).factory("GetSyncStatusMsg",[function(){return function(a){var b,c,d,e=a.status,f="",g="Start sync process";switch(b=e,c="icon-cloud-"+b,e){case"never updated":b="never",c="icon-cloud-na disabled",d='Sync not performed. Click to start it now.';break;case"none":case"":f="btn-disabled",b="n/a",c="icon-cloud-na disabled",d='Cloud source not configured. Click to update.',g=d;break;case"failed":d="Sync failed. Click to view log.";break;case"successful":d="Sync completed. Click to view log.";break;case"updating":d="Sync running"}return{"class":c,tooltip:d,status:b,launch_class:f,launch_tip:g}}}]).factory("SourceChange",["GetBasePath","CredentialList","LookUpInit","Empty",function(a,b,c,d){return function(e){var f,g,h=e.scope,i=e.form;d(h.source)||("file"===h.source.value?h.sourcePathRequired=!0:(h.sourcePathRequired=!1,h.source_path="",h[i.name+"_form"].source_path.$setValidity("required",!0)),"rax"===h.source.value?(h.source_region_choices=h.rax_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])):"ec2"===h.source.value&&(h.source_region_choices=h.ec2_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])),("rax"===h.source.value||"ec2"===h.source.value)&&(f="rax"===h.source.value?"rax":"aws",g=a("credentials")+"?cloud=true&kind="+f,c({url:g,scope:h,form:i,list:b,field:"credential"})))}}]).factory("GroupsCancelUpdate",["Rest","ProcessErrors","Alert","Wait","Find",function(a,b,c,d,e){return function(f){var g,h=f.scope,i=f.tree_id;h.removeCancelUpdate&&h.removeCancelUpdate(),h.removeCancelUpdate=h.$on("CancelUpdate",function(e,f){a.setUrl(f),a.post().success(function(){d("stop"),c("Inventory Sync Cancelled",'Your request to cancel the sync process was submitted to the task manger. Click the button to monitor the status.',"alert-info")}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+f+" failed. POST status: "+c})})}),h.removeCheckCancel&&h.removeCheckCancel(),h.removeCheckCancel=h.$on("CheckCancel",function(e,f,g){var i=g?g:f;i+="cancel/",a.setUrl(i),a.get().success(function(a){a.can_cancel?h.$emit("CancelUpdate",i):(d("stop"),c("Cancel Inventory Sync",'Either you do not have access or the sync process completed. Click the button to view the latest status.',"alert-info"))}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+i+" failed. GET status: "+c})})}),g=e({list:h.groups,key:"id",val:i}),h.selected_tree_id=g.id,h.selected_group_id=g.group_id,!g||"updating"!==g.status&&"pending"!==g.status?c("Cancel Inventory Sync",'The sync process completed. Click the to view the latest status.',"alert-info"):(d("start"),a.setUrl(g.related.inventory_source),a.get().success(function(a){h.$emit("CheckCancel",a.related.last_update,a.related.current_update)}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+g.related.inventory_source+" failed. GET status: "+c})}))}}]).factory("GroupsAdd",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","ParseTypeChange","GroupsEdit","Wait","GetChoices","GetSourceTypeOptions","LookUpInit","BuildTree","SourceChange","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){return function(b){var c,d=b.inventory_id,i=void 0!==b.group_id?b.group_id:null,m=b.scope,q=null!==i?k("groups")+i+"/children/":k("inventory")+d+"/groups/",u=g,v=h,w=v.inject(u,{mode:"add",modal:!0,related:!1,show_modal:!1});$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),w.formModalActionLabel="Save",w.formModalCancelShow=!0,w.parseType="yaml",w.source=null,l(w),v.reset(),w.removeAddTreeRefreshed&&w.removeAddTreeRefreshed(),w.removeAddTreeRefreshed=w.$on("GroupTreeRefreshed",function(){a.formModalHeader=null,a.formModalCancleShow=null,a.formModalActionLabel=null,n("stop"),$("#form-modal").modal("hide"),w.removeAddTreeRefreshed()}),w.removeSaveComplete&&w.removeSaveComplete(),w.removeSaveComplete=w.$on("SaveComplete",function(a,b,c){c||(w.searchCleanup&&w.searchCleanup(),w.formModalActionDisabled=!1,r({scope:m,inventory_id:d,refresh:!0,new_group_id:b}),t())}),w.removeFormSaveSuccess&&w.removeFormSaveSuccess(),w.removeFormSaveSuccess=w.$on("formSaveSuccess",function(a,b,c){var d,g,h,i,k=!1,l={};if(null!==w.source.value&&""!==w.source.value){for(l.group=b,l.source=w.source.value,l.source_path=w.source_path,l.credential=w.credential,l.overwrite=w.overwrite,l.overwrite_vars=w.overwrite_vars,l.update_on_launch=w.update_on_launch,d=$("#s2id_group_source_regions").select2("data"),g=[],h=0;h"+A.summary_fields.group.name+". Use the Refresh button to monitor the status.","alert-info"):o({scope:A,group_id:d,url:A.group_update_url,group_name:A.name,group_source:A.source.value})},A.sourceChange=function(){v({scope:A,form:g})}}}]).factory("GroupsDelete",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","Wait","BuildTree","Find",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){return function(a){var b,c=a.scope,d=a.tree_id,f=a.inventory_id,g=n({list:c.groups,key:"id",val:d}),h=k("inventory")+f+"/groups/";b=function(){$("#prompt-modal").on("hidden.bs.modal",function(){l("start")}),$("#prompt-modal").modal("hide"),e.setUrl(h),e.post({id:g.group_id,disassociate:1}).success(function(){$("#prompt-modal").off(),c.$emit("GroupDeleteCompleted")}).error(function(a,b){l("stop"),j(c,a,b,null,{hdr:"Error!",msg:"Call to "+h+" failed. POST returned status: "+b})})},i({hdr:"Delete Group",body:"
Are you sure you want to delete group "+g.name+"?
",action:b,"class":"btn-danger"})}}]).factory("ShowUpdateStatus",["$rootScope","$location","$log","$routeParams","Rest","Alert","GenerateForm","Prompt","ProcessErrors","GetBasePath","FormatDate","InventoryStatusForm","Wait","Empty","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){return function(a){function b(a){var b,d;return b=a.match(/\n/g),d=b?b.length:1,d>c?c:d}var c,d,h,j,n,p,q,r=a.group_name,s=a.last_update,t=g,u=l,v=a.license_error;void 0===s||null===s||""===s?(m("stop"),f("Missing Configuration","The selected group is not configured for inventory sync. Edit the group and provide Source information.","alert-info")):(d='
\n
\n',$("#inventory-modal-container").empty().append(d),h=t.inject(u,{mode:"edit",id:"form-container",breadCrumbs:!1,related:!1}),j=$(document).width(),n=$("body").height(),j>1199?(p=675,q=750>n?n-20:750,c=18):1199>=j&&j>=768?(p=550,q=620>n?n-15:620,c=12):(p=j-20,q=500>n?n:500,c=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:p,height:q,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#inventory-modal-container").empty(),o()},open:function(){m("stop")}}),e.setUrl(s),e.get().success(function(a){for(var c in u.fields)a[c]&&(h[c]="created"===c?k(new Date(a[c])):a[c]);h.license_error=v,h.status_rows=b(a.status),h.stdout_rows=b(a.result_stdout),h.traceback_rows=b(a.result_traceback),$("#status-modal-dialog").dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(h,a,b,null,{hdr:"Error!",msg:"Failed to retrieve last update: "+s+". GET status: "+b})}))}}]),angular.module("HostsHelper",["RestServices","Utilities","ListGenerator","HostListDefinition","SearchHelper","PaginationHelpers","ListGenerator","AuthService","HostsHelper","InventoryHelper","RelatedSearchHelper","InventoryFormDefinition","SelectionHelper","HostGroupsFormDefinition"]).factory("SetEnabledMsg",[function(){return function(a){a.enabledToolTip=a.has_inventory_sources?a.enabled?"Host is available":"Host is not available":a.enabled?"Host is available. Click to toggle.":"Host is not available. Click to toggle."}}]).factory("SetHostStatus",["SetEnabledMsg",function(a){return function(b){b.activeFailuresLink="/#/hosts/"+b.id+"/job_host_summaries/?inventory="+b.inventory+"&host_name="+encodeURI(b.name),b.has_active_failures===!0?(b.badgeToolTip="Most recent job failed. Click to view jobs.",b.active_failures="failed"):b.has_active_failures===!1&&null===b.last_job?(b.has_active_failures="none",b.badgeToolTip="No job data available.",b.active_failures="n/a"):b.has_active_failures===!1&&null!==b.last_job&&(b.badgeToolTip="Most recent job successful. Click to view jobs.",b.active_failures="success"),b.enabled_flag=b.enabled,a(b)}}]).factory("SetStatus",["SetEnabledMsg","Empty",function(a,b){return function(c){function d(a){return a.length>25?a.substr(0,25)+"...":a}function e(a){var b,c,e;if(a.has_active_failures===!0||a.has_active_failures===!1&&null!==a.last_job)if(a.has_active_failures===!0?(a.badgeToolTip="Most recent job failed. Click to view jobs.",a.active_failures="failed"):(a.badgeToolTip="Most recent job successful. Click to view jobs.",a.active_failures="success"),a.summary_fields.recent_jobs.length>0){for(e=a.summary_fields.recent_jobs.sort(function(a,b){return-1*(a-b)}),h="Recent Jobs",g='
";else a.has_active_failures===!1&&null===a.last_job&&(a.has_active_failures="none",a.badgeToolTip="No job data available.",a.active_failures="n/a");a.job_status_html=g,a.job_status_title=h}var f,g,h,i=c.scope,j=c.host;if(b(j))for(f=0;fAre you sure you want to delete host "+j+" from group "+n.name+"?":"
\n",d=j("hosts")+l+"/",f=o.inject(null,{mode:"edit",modal:!0,related:!1,html:c}),b=0;bGroups',f.formModalCancelShow=!0,f.formModalActionDisabled=!0,$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),f.hostGroupChangeRemove&&f.hostGroupChangeRemove(),f.hostGroupChangeRemove=f.$on("hostGroupChange",function(){p.pop(),0===p.length&&(h=function(){setTimeout(function(){m("stop")},500)},k({scope:f,inventory_id:n,group_id:f.group_id,action:h}))}),f.formModalAction=function(){var a,b,c;for($("#form-modal").modal("hide"),m("start"),a=0;a0?(f.assignedGroups=null,f.leftButtonDisabled=!0,f.rightButtonDisabled=!1):f.rightButtonDisabled=!0},f.rightChange=function(){null!==f.assignedGroups&&f.assignedGroups.length>0?(f.selectedGroups=null,f.leftButtonDisabled=!1,f.rightButtonDisabled=!0):f.leftButtonDisabled=!0},f.moveLeft=function(){var a,b,c,d;for(a=0;af.available_groups[b].name.toLowerCase()&&f.assignedGroups[a].name.toLowerCase()f.host_groups[b].name.toLowerCase()&&f.selectedGroups[a].name.toLowerCase()0){for(j("stop"),u+='\n",m=angular.element(document.getElementById("password-body")),m.html(u),c(m.contents())(q),$("#password-modal").modal(),$("#password-modal").on("shown.bs.modal",function(){$("#password-body").find('input[type="password"]:first').focus()})}else q.startJob()}}]).factory("SubmitJob",["PromptPasswords","$compile","Rest","$location","GetBasePath","CredentialList","LookUpInit","CredentialForm","ProcessErrors","JobTemplateForm","Wait",function(a,b,c,d,e,f,g,h,i,j,k){return function(b){function l(b){var e,f,g;m.credentialWatchRemove&&m.credentialWatchRemove(),e=(new Date).toISOString(),f=b.related.jobs?b.related.jobs:b.related.job_template+"jobs/",g=o?o:b.name,k("start"),c.setUrl(f),c.post({name:g+" "+e,description:b.description,job_template:b.id,inventory:b.inventory,project:b.project,playbook:b.playbook,credential:b.credential,forks:b.forks,limit:b.limit,verbosity:b.verbosity,extra_vars:b.extra_vars}).success(function(b){m.job_id=b.id,b.passwords_needed_to_start.length>0?a({scope:m,passwords:b.passwords_needed_to_start,start_url:b.related.start,form:h}):(c.setUrl(b.related.start),c.post().success(function(){k("stop");var a=d.path().replace(/^\//,"").split("/")[0];"jobs"===a?m.refresh():d.path("/jobs")}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to start job. POST returned status: "+b})}))}).error(function(a,b){k("stop"),i(m,a,b,null,{hdr:"Error!",msg:"Failed to create job. POST returned status: "+b})})}var m=b.scope,n=b.id,o=b.template?b.template:null,p=d.path().replace(/^\//,"").split("/")[0],q=e(p)+n+"/";k("start"),c.setUrl(q),c.get().success(function(a){m.credential="",""===a.credential||null===a.credential?(k("stop"),m.credentialWatchRemove&&m.credentialWatchRemove(),m.credentialWatchRemove=m.$watch("credential",function(b,c){b!==c&&""!==m.credential&&null!==m.credential&&void 0!==m.credential&&(a.credential=m.credential,l(a))}),g({scope:m,form:j,current_item:null,list:f,field:"credential",hdr:"Credential Required"}),m.lookUpCredential()):l(a)}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to get job template details. GET returned status: "+b})})}}]).factory("ProjectUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","ProjectsForm","Wait",function(a,b,c,d,e,f,g,h,i){return function(b){var d=b.scope,j=b.project_id,k=e("projects")+j+"/update/";d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(){i("stop"),g("Update Started","The request to start the SCM update process was submitted. To monitor the update status, refresh the page by clicking the Refresh button.","alert-info"),d.refresh()}),d.removeSCMSubmit&&d.removeSCMSubmit(),d.removeSCMSubmit=d.$on("SCMSubmit",function(b,c,e){a({scope:d,passwords:c,start_url:k,form:h,extra_html:e})}),i("start"),c.setUrl(k),c.get().success(function(a){var b,c;if(i("stop"),a.can_update){for(c="",b=0;b\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="\n",d.projects[b].scm_username&&(c+='
\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="
\n");break}c+="",d.$emit("SCMSubmit",a.passwords_needed_to_update,c)}else g("Permission Denied","You do not have access to update this project. Please contact your system administrator.","alert-danger")}).error(function(a,b){f(d,a,b,null,{hdr:"Error!",msg:"Failed to get project update details: "+k+" GET status: "+b})})}}]).factory("InventoryUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","GroupForm","BuildTree","Wait",function(a,b,c,d,e,f,g,h,i,j){return function(b){var d=b.scope,e=b.url,i=b.group_id,k=b.tree_id;d.removeHostReloadComplete&&d.removeHostReloadComplete(),d.removeHostReloadComplete=d.$on("HostReloadComplete",function(){j("stop"),g("Update Started",'Your request to start the inventory sync process was submitted. Monitor progress by clicking the button.',"alert-info"),d.removeHostReloadComplete&&d.removeHostReloadComplete()}),d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(a,b){"started"===b&&(d.refreshGroups?(d.selected_tree_id=k,d.selected_group_id=i,d.refreshGroups()):d.refresh&&d.refresh(),d.$emit("HostReloadComplete"))}),d.removeInventorySubmit&&d.removeInventorySubmit(),d.removeInventorySubmit=d.$on("InventorySubmit",function(b,c,f){a({scope:d,passwords:c,start_url:e,form:h,extra_html:f})}),j("start"),c.setUrl(e),c.get().success(function(a){a.can_update?d.$emit("InventorySubmit",a.passwords_needed_to_update):(j("stop"),g("Permission Denied","You do not have access to run the update. Please contact your system administrator.","alert-danger"))}).error(function(a,b){j("stop"),f(d,a,b,null,{hdr:"Error!",msg:"Failed to get inventory_source details. "+e+"GET status: "+b})})}}]),angular.module("JobsHelper",["Utilities","FormGenerator","JobSummaryDefinition","InventoryHelper"]).factory("JobStatusToolTip",[function(){return function(a){var b;switch(a){case"successful":case"success":b="There were no failed tasks.";break;case"failed":b="Some tasks encountered errors.";break;case"canceled":b="Stopped by user request.";break;case"new":b="In queue, waiting on task manager.";break;case"waiting":b="SCM Update or Inventory Update is executing.";break;case"pending":b="Not in queue, waiting on task manager.";break;case"running":b="Playbook tasks executing."}return b}}]).factory("ShowJobSummary",["Rest","Wait","GetBasePath","FormatDate","ProcessErrors","GenerateForm","JobSummary","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h){return function(i){function j(a){var b=a.match(/\n/g),c=b?b.length:1;return c>p?20:c}var k,l,m,n,o,p,q,r,s=i.job_id,t=f,u=g;r='
Only allow the user or team to view the inventory.
\n
Write
\n
Allow the user or team to modify hosts and groups contained in the inventory, add new hosts and groups, and perform inventory sync operations.\n
Admin
\n
Allow the user or team full access to the inventory. This includes reading, writing, deletion of the inventory and inventory sync operations.
\n
\n"):(b.projectrequired=!0,b.permissionTypeHelp="
\n
Run
\n
Allow the user or team to perform a live deployment of the project against the inventory. In Run mode modules will be executed, and changes to the inventory will occur.
\n
Check
\n
Only allow the user or team to deploy the project against the inventory as a dry-run operation. In Check mode, module operations will only be simulated. No changes will occur.
\n
\n"),c&&(b.permission_type="Inventory"===b.category?"read":"run")}}]),angular.module("ProjectPathHelper",["RestServices","Utilities"]).factory("GetProjectPath",["Alert","Rest","GetBasePath","ProcessErrors",function(a,b,c,d){return function(a){function e(a){var b,c,d=[],e=[];for(b=0;b\n',$("#projects-modal-container").empty().append(b),c=q.inject(r,{mode:"edit",id:"form-container",related:!1,breadCrumbs:!1}),q.reset(),d=$(document).width(),f=$("body").height(),d>1199?(h=675,j=750>f?f-20:750,n=20):1199>=d&&d>=768?(h=550,j=620>f?f-15:620,n=15):(h=d-20,j=500>f?f:500,n=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:h,height:j,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#projects-modal-container").empty()},open:function(){m("stop")}}),e.setUrl(p),e.get().success(function(a){var b,d=a;for(b in r.fields)d[b]?c[b]="created"===b?k(new Date(d[b])):d[b]:d.summary_fields.project[b]&&(c[b]=d.summary_fields.project[b]);$("#status-modal-dialog").dialog({title:d.summary_fields.project.name+" Status"}).dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(c,a,b,r,{hdr:"Error!",msg:"Failed to retrieve status of project: "+o+". GET status: "+b})})}}]),angular.module("SelectionHelper",["Utilities","RestServices"]).factory("SelectionInit",["Rest","Alert","ProcessErrors","ReturnToCaller","Wait",function(a,b,c,d,e){return function(b){var f,g=b.scope,h=b.list,i=b.url,j=b.returnToCaller;f=void 0!==b.selected?b.selected:[],g.formModalActionDisabled=!0,g.disableSelectBtn=!0,g["toggle_"+h.iterator]=function(a,b){var c,d,e;for(c=0;c0?(g.formModalActionDisabled=!1,g.disableSelectBtn=!1):(g.formModalActionDisabled=!0,g.disableSelectBtn=!0)},g.finishSelection=function(){function b(){f=[],void 0!==j?d(j):($("#form-modal").modal("hide"),g.$emit("modalClosed"))}function k(b){a.post(b).success(function(a,b){m.push({result:"success",data:a,status:b}),g.$emit("callFinished")}).error(function(a,b,c){m.push({result:"error",data:a,status:b,headers:c}),g.$emit("callFinished")})}a.setUrl(i);var l,m=[];if(g.formModalActionDisabled=!0,g.disableSelectBtn=!0,e("start"),g.callFinishedRemove&&g.callFinishedRemove(),g.callFinishedRemove=g.$on("callFinished",function(){var a,d=0;if(m.length===f.length){for(e("stop"),a=0;a0)for(l=0;lh)h++,setTimeout(1e3,e());else if("success"===g.status)return d(a)}var f,g={},h=0;return null===c.apiDefaults||void 0===c.apiDefaults?(f="/api/v1/",b.setUrl(f),b.get().success(function(a){var b,d=a;for(b in d)switch(b){case"organizations":d[b].iterator="organization";break;case"jobs":d[b].iterator="job";break;case"users":d[b].iterator="user";break;case"teams":d[b].iterator="team";break;case"hosts":d[b].iterator="host";break;case"groups":d[b].iterator="group";break;case"projects":d[b].iterator="project";break;case"inventories":d[b].iterator="inventory"}c.apiDefaults=d,g={status:"success"}}).error(function(a,b){g={status:"error",msg:"Call to "+f+" failed. GET returned status: "+b}}),e()):d(a)}}]),angular.module("InventoryHelper",["RestServices","Utilities","OrganizationListDefinition","ListGenerator","AuthService","InventoryHelper","InventoryFormDefinition","ParseHelper","SearchHelper"]).factory("WatchInventoryWindowResize",["ApplyEllipsis",function(a){return function(){var b;$(window).resize(function(){clearTimeout(b),b=setTimeout(function(){$("#groups_table .name-column").each(function(){var a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%";$(this).find(".group-name").css({width:e})}),a("#groups_table .group-name a"),a("#hosts_table .host-name a")},100)})}}]).factory("SaveInventory",["InventoryForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","Wait",function(a,b,c,d,e,f,g,h,i){return function(e){var f,h,j,k=e.scope,l=a,m=g("inventory");i("start");try{if(h="json"===k.inventoryParseType?JSON.parse(k.inventory_variables):jsyaml.load(k.inventory_variables),"object"!=typeof h)throw"failed to return an object!";j={};for(f in l.fields)"inventory_variables"!==f&&(l.fields[f].realName?j[l.fields[f].realName]=k[f]:j[f]=k[f]);b.setUrl(m+k.inventory_id+"/"),b.put(j).success(function(a){k.inventory_variables?(b.setUrl(a.related.variable_data),b.put(h).success(function(){i("stop"),k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory varaibles. PUT returned status: "+b})})):k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory. POST returned status: "+b})})}catch(n){i("stop"),c("Error","Error parsing inventory variables. Parser returned: "+n)}}}]).factory("EditInventoryProperties",["InventoryForm","GenerateForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","SaveInventory","Wait","Store","SearchInit",function(a,b,c,d,e,f,g,h,i,j,k,l,m){return function(n){var o,p=n.scope,q=n.inventory_id,r=b,s=a,t={},u=l("CurrentSearchParams");s.well=!1,o=r.inject(s,{mode:"edit",modal:!0,related:!1,modal_show:!1}),s.well=!0,i(o,"inventory_variables","inventoryParseType"),o.inventoryParseType="yaml",o.formModalActionLabel="Save",o.formModalCancelShow=!0,o.formModalInfo=!1,o.formModalHeader="Inventory Properties",k("start"),c.setUrl(h("inventory")+q+"/"),c.get().success(function(a){var b,c;for(b in s.fields){if("inventory_variables"===b){if($.isEmptyObject(a.variables)||"{}"===a.variables||"null"===a.variables||""===a.variables)o.inventory_variables="---";else try{c=JSON.parse(a.variables),o.inventory_variables=jsyaml.safeDump(c)}catch(e){d("Variable Parse Error","Attempted to parse variables for inventory: "+q+". Parse returned: "+e),console&&(console.log(e),console.log("data:"),console.log(a.variables)),o.inventory_variables="---"}t.inventory_variables=o.variables}else"inventory_name"===b?(o[b]=a.name,t[b]=o[b]):"inventory_description"===b?(o[b]=a.description,t[b]=o[b]):a[b]&&(o[b]=a[b],t[b]=o[b]);s.fields[b].sourceModel&&a.summary_fields&&a.summary_fields[s.fields[b].sourceModel]&&(o[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField],t[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField])}f({scope:o,form:s,current_item:o.organization,list:g,field:"organization"}),k("stop"),$("#form-modal").modal("show")}).error(function(a,b){e(o,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+q+". GET returned: "+b})}),o.removeInventorySaved&&o.removeInventorySaved(),o.removeInventorySaved=o.$on("InventorySaved",function(){$("#form-modal").modal("hide"),o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1}),p.$emit("RefreshInventories")}),o.cancelModal=function(){o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1})},o.formModalAction=function(){p.inventory_id=q,p.inventory_name=o.inventory_name,j({scope:o})}}}]),angular.module("md5Helper",["RestServices","Utilities"]).factory("md5Setup",[function(){return function(a){var b=a.scope,c=a.master,d=a.check_field,e=a.default_val;b[d]=e,c[d]=e,b.genMD5=function(a){var c=new Date;b[a]=$.md5("AnsibleWorks"+c.getTime())},b.toggleCallback=function(a){"false"===b.allow_callbacks&&(b[a]="")},b.selectAll=function(a){$('input[name="'+a+'"]').focus().select()}}}]),angular.module("RefreshRelatedHelper",["RestServices","Utilities","PaginationHelpers"]).factory("RefreshRelated",["ProcessErrors","Rest","Wait","PageRangeSetup",function(a,b,c,d){return function(e){var f=e.scope,g=e.set,h=e.iterator,i=e.url;b.setUrl(i),b.get().success(function(a){d({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[g]=a.results,f[h+"Loading"]=!1,f[h+"HoldInput"]=!1,c("stop"),f.$emit("related"+g)}).error(function(b,c){a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RefreshHelper",["RestServices","Utilities","PaginationHelpers"]).factory("Refresh",["ProcessErrors","Rest","Wait","Empty","PageRangeSetup",function(a,b,c,d,e){return function(d){var f=d.scope,g=d.set,h=d.iterator,i=d.url;f.current_url=i,b.setUrl(i),b.get().success(function(a){var b,d;for(e({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[h+"Loading"]=!1,b=1;3>=b;b++)d=1===b?"":b,f[h+"HoldInput"+d]=!1;f[g]=a.results,window.scrollTo(0,0),c("stop"),f.$emit("PostRefresh")}).error(function(b,c){f[h+"HoldInput"]=!1,a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RelatedSearchHelper",["RestServices","Utilities","RefreshRelatedHelper"]).factory("RelatedSearchInit",["$timeout","Alert","Rest","RefreshRelated","Wait",function(a,b,c,d,e){return function(a){function b(a){var b,c,d,e;for(e in h.related)if("tree"!==h.related[e].type&&(void 0===a||a===h.related[e].iterator)){b=h.related[e].iterator;for(d in h.related[e].fields)if(h.related[e].fields[d].key){f[b+"SearchField"]=d,f[b+"SearchFieldLabel"]=h.related[e].fields[d].label;break}f[b+"SortOrder"]=null,f[b+"SearchType"]="icontains",f[b+"SearchTypeLabel"]="Contains",f[b+"SearchValue"]=null,f[b+"SelectShow"]=!1,f[b+"ShowStartBtn"]=!0,f[b+"HideAllStartBtn"]=!1,c=f[b+"SearchField"],!h.related[e].fields[c].searchType||"boolean"!==h.related[e].fields[c].searchType&&"select"!==h.related[e].fields[c].searchType||(f[b+"SelectShow"]=!0,f[b+"SearchSelectOpts"]=h.fields[c].searchOptions),h.related[e].fields[c].searchType&&"gtzero"===h.related[e].fields[c].searchType&&(f[b+"InputHide"]=!0)}}var c,f=a.scope,g=a.relatedSets,h=a.form;b(),f.resetSearch=function(a){b(a),f.search(a)},f.setSearchField=function(a,b,c){var d,e;for(e in h.related)h.related[e].iterator===a&&(d=h.related[e].fields[b]);f[a+"SearchFieldLabel"]=c,f[a+"SearchField"]=b,f[a+"SearchValue"]="",f[a+"SelectShow"]=!1,f[a+"InputHide"]=!1,f[a+"ShowStartBtn"]=!0,void 0!==d.searchType&&"gtzero"===d.searchType&&(f[a+"InputHide"]=!0,f[a+"ShowStartBtn"]=!1),void 0===d.searchType||"boolean"!==d.searchType&&"select"!==d.searchType||(f[a+"SelectShow"]=!0,f[a+"SearchSelectOpts"]=d.searchOptions),void 0!==d.searchType&&"int"===d.searchType&&(f[a+"SearchType"]="int"),f.search(a)},f.setSearchType=function(a,b,c){f[a+"SearchTypeLabel"]=c,f[a+"SearchType"]=b,f.search(a)},f.startSearch=function(a,b){13===a.keyCode&&f.search(b)},f.search=function(a){e("start"),f[a+"Loading"]=!0,f[a+"HoldInput"]=!0,f[a+"SearchValue"]&&(f[a+"ShowStartBtn"]=!1),"host"===a&&"has_active_failures"===f.hostSearchField&&(f.hostFailureFilter=f.hostSearchSelectValue&&1===f.hostSearchSelectValue.value?!0:!1);var b,i,j,k,l;for(i in g)if(g[i].iterator===a){j=i,k=g[i].url;for(b in h.related[i].fields)h.related[i].fields[b].key&&(l=h.related[i].fields[b].desc?"-"+b:b);break}l=null===f[a+"SortOrder"]?l:f[a+"SortOrder"],c=h.related[j].fields[f[a+"SearchField"]],f[a+"SelectShow"]===!1&&""!==f[a+"SearchValue"]&&void 0!==f[a+"SearchValue"]||f[a+"SelectShow"]&&f[a+"SearchSelectValue"]||c.searchType&&"gtzero"===c.searchType?(f[a+"SearchParams"]=c.sourceModel?c.sourceModel+"__"+c.sourceField+"__":c.searchField?c.searchField+"__":f[a+"SearchField"]+"__",f[a+"SearchParams"]+=!c.searchType||"int"!==c.searchType&&"boolean"!==c.searchType?c.searchType&&"gtzero"===c.searchType?"gt=0":f[a+"SearchType"]+"=":"int=",!c.searchType||"boolean"!==c.searchType&&"select"!==c.searchType?(void 0===c.searchType||"gtzero"===c.searchType)&&(f[a+"SearchParams"]+=encodeURI(f[a+"SearchValue"])):f[a+"SearchParams"]+=f[a+"SearchSelectValue"].value,f[a+"SearchParams"]+=l?"&order_by="+encodeURI(l):""):f[a+"SearchParams"]=l?"order_by="+encodeURI(l):"",f[a+"Page"]=0,k+=k.match(/\/$/)?"?":"&",k+=f[a+"SearchParams"],k+=f[a+"PageSize"]?"&page_size="+f[a+"PageSize"]:"",d({scope:f,set:j,iterator:a,url:k})},f.sort=function(a,b){var c,d,e,g;$("."+a+" .list-header").each(function(){if($(this).attr("id")!==a+"-"+b+"-header"){var c=$(this).find("i");c.attr("class","icon-sort")}}),d=$("#"+a+"-"+b+"-header i"),e="",d.hasClass("icon-sort")?(d.removeClass("icon-sort"),d.addClass("icon-sort-up")):d.hasClass("icon-sort-up")?(d.removeClass("icon-sort-up"),d.addClass("icon-sort-down"),e="-"):d.hasClass("icon-sort-down")&&(d.removeClass("icon-sort-down"),d.addClass("icon-sort-up"));for(g in h.related)h.related[g].iterator===a&&(c=h.related[g].fields[b].sourceModel?e+h.related[g].fields[b].sourceModel+"__"+h.related[g].fields[b].sourceField:e+b);f[a+"SortOrder"]=c,f.search(a)}}}]),angular.module("SearchHelper",["RestServices","Utilities","RefreshHelper"]).factory("SearchInit",["Alert","Rest","Refresh","$location","GetBasePath","Empty","$timeout","Wait","Store",function(a,b,c,d,e,f,g,h,i){return function(a){function b(a){var b,c,d,e;e=void 0===a||1===a?"":a,l[p+"SearchField"+e]="",l[p+"SearchFieldLabel"+e]="";for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&o.fields[c].key){o.fields[c].sourceModel?(d=o.fields[c].sourceModel+"__"+o.fields[c].sourceField,r=o.fields[c].desc?"-"+d:d):r=o.fields[c].desc?"-"+c:c,(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)&&(l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label);break}if(f(l[p+"SearchField"+e]))for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)){l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label;break}l[p+"SearchType"+e]="icontains",l[p+"SearchTypeLabel"+e]="Contains",l[p+"SearchParams"+e]="",l[p+"SearchValue"+e]="",l[p+"SelectShow"+e]=!1,l[p+"HideSearchType"+e]=!1,l[p+"InputDisable"+e]=!1,l[p+"ExtraParms"+e]="",l[p+"ShowStartBtn"+e]=!0,l[p+"HideAllStartBtn"+e]=!1,l[p+"SearchPlaceholder"+e]=o.fields[l[p+"SearchField"+e]]&&o.fields[l[p+"SearchField"+e]].searchPlaceholder?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]:o.fields[l[p+"SearchField"+e]].searchPlaceholder:"Search",l[p+"InputDisable"+e]=o.fields[l[p+"SearchField"+e]]&&"all"===o.fields[l[p+"SearchField"+e]].searchObject?!0:!1,b=l[p+"SearchField"+e],o.fields[b]&&(!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType||(l[p+"SelectShow"+e]=!0,l[p+"SearchSelectOpts"+e]=o.fields[b].searchOptions),o.fields[b].searchType&&"int"===o.fields[b].searchType&&(l[p+"HideSearchType"+e]=!0),o.fields[b].searchType&&"gtzero"===o.fields[b].searchType&&(l[p+"InputHide"+e]=!0))}var e,g,j,k,l=a.scope,m=a.set,n=a.url,o=a.list,p=a.iterator?a.iterator:o.iterator,q=a.setWidgets===!1?!1:!0,r=a.sort_order||"";if(q)for(e=o.searchWidgets?o.searchWidgets:1,g=1;e>=g;g++)j=1===g?"":g,$("#search-widget-container"+j)&&b(g);k={set:m,defaultUrl:n,list:o,iterator:p,sort_order:r},i("CurrentSearchParams",k),l.setSearchField=function(a,b,c,d){var e=void 0===d||1===d?"":d;l[a+"SearchFieldLabel"+e]=c,l[a+"SearchField"+e]=b,l[a+"SearchValue"+e]="",l[a+"SelectShow"+e]=!1,l[a+"HideSearchType"+e]=!1,l[a+"InputHide"+e]=!1,l[a+"SearchType"+e]="icontains",l[a+"InputDisable"+e]="all"===o.fields[b].searchObject?!0:!1,l[a+"ShowStartBtn"+e]=!0,l[a+"SearchPlaceholder"+e]=o.fields[l[a+"SearchField"+e]]&&o.fields[l[a+"SearchField"+e]].searchPlaceholder?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]:o.fields[l[a+"SearchField"+e]].searchPlaceholder:"Search",o.fields[b].searchType&&"gtzero"===o.fields[b].searchType?(l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1,l.search(a)):o.fields[b].searchSingleValue?(l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"SearchSelectValue"+e]="boolean"===o.fields[b].searchType&&"true"===o.fields[b].searchValue?{value:1}:"boolean"===o.fields[b].searchType&&"false"===o.fields[b].searchValue?{value:0}:{value:o.fields[b].searchValue},l[a+"ShowStartBtn"+e]=!1):"in"===o.fields[b].searchType?(l[a+"SearchType"+e]="in",l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1):!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType&&"select_or"!==o.fields[b].searchType?o.fields[b].searchType&&"int"===o.fields[b].searchType?l[a+"SearchType"+e]="int":o.fields[b].searchType&&"isnull"===o.fields[b].searchType&&(l[a+"SearchType"+e]="isnull",l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]="true",l[a+"ShowStartBtn"+e]=!1):(l[a+"SelectShow"+e]=!0,l[a+"SearchSelectOpts"+e]=o.fields[b].searchOptions),l.search(a)},l.resetSearch=function(a){var c,e=o.searchWidgets?o.searchWidgets:1;for(c=1;e>=c;c++)b(c);window.location="/#"+d.path(),l.search(a)},l.removeDoSearch&&l.removeDoSearch(),l.removeDoSearch=l.$on("doSearch",function(a,b,d,e){l[b+"Loading"]=void 0===e||e===!0?!0:!1;var f,g=n;l[b+"Page"]=d?parseInt(d)-1:0,l[b+"SearchParams"]&&(g+=/\/$/.test(g)?"?"+l[b+"SearchParams"]:"&"+l[b+"SearchParams"]),f=/\/$/.test(g)?"?":"&",g+=l[b+"_page_size"]?f+"page_size="+l[b+"_page_size"]:"",d&&(f=/\/$/.test(g)?"?":"&",g+=f+"page="+d),l[b+"ExtraParms"]&&(f=/\/$/.test(g)?"?":"&",g+=f+l[b+"ExtraParms"]),g=g.replace(/\&\&/,"&"),c({scope:l,set:m,iterator:b,url:g})}),l.removePrepareSearch&&l.removePrepareSearch(),l.removePrepareSearch=l.$on("prepareSearch",function(a,b,c,d,e){h("start"),l[b+"SearchParams"]="";var f,g,i=o.searchWidgets?o.searchWidgets:1;for(f=1;i>=f;f++)g=1===f?"":f,$("#search-widget-container"+g)&&o.fields[l[b+"SearchField"+g]]&&o.fields[l[b+"SearchField"+g]].searchObject&&("all"!==o.fields[l[b+"SearchField"+g]].searchObject?(l[b+"HideAllStartBtn"+g]=!1,l[b+"SearchValue"+g]?(l[b+"ShowStartBtn"+g]=!1,l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+g]].searchOnID?"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__id="+l[b+"SearchValue"+g]:"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__name__icontains="+l[b+"SearchValue"+g]):(l[b+"ShowStartBtn"+g]=!0,l[b+"SearchParams"]+="&"+o.fields[l[b+"SearchField"+g]].searchField+"="+o.fields[l[b+"SearchField"+g]].searchObject)):l[b+"HideAllStartBtn"+g]=!0);l.$emit("prepareSearch2",b,c,d,e)}),l.removePrepareSearch2&&l.removePrepareSearch2(),l.removePrepareSearch2=l.$on("prepareSearch2",function(a,b,c,d,e){var g,h,i=o.searchWidgets?o.searchWidgets:1;for(g=1;i>=g;g++)h=1===g?"":g,l[b+"HoldInput"+h]=!0,$("#search-widget-container"+h)&&o.fields[l[b+"SearchField"+h]]&&!o.fields[l[b+"SearchField"+h]].searchObject&&(l[b+"ShowStartBtn"+h]=l[b+"SearchValue"+h]?!1:!0,(!l[b+"SelectShow"+h]&&!f(l[b+"SearchValue"+h])||l[b+"SelectShow"+h]&&l[b+"SearchSelectValue"+h]||o.fields[l[b+"SearchField"+h]]&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+h]].searchField?"&"+o.fields[l[b+"SearchField"+h]].searchField+"__":o.fields[l[b+"SearchField"+h]].sourceModel?"&"+o.fields[l[b+"SearchField"+h]].sourceModel+"__"+o.fields[l[b+"SearchField"+h]].sourceField+"__":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?"&"+l[b+"SearchField"+h]+"__":"&"+l[b+"SearchField"+h]+"__",l[b+"SearchParams"]+=!o.fields[l[b+"SearchField"+h]].searchType||"int"!==o.fields[l[b+"SearchField"+h]].searchType&&"boolean"!==o.fields[l[b+"SearchField"+h]].searchType?o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType?"gt=0":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?l[b+"SearchType"+h]+"=":"iexact=":"int=",!o.fields[l[b+"SearchField"+h]].searchType||"boolean"!==o.fields[l[b+"SearchField"+h]].searchType&&"select"!==o.fields[l[b+"SearchField"+h]].searchType?(!o.fields[l[b+"SearchField"+h]].searchType||o.fields[l[b+"SearchField"+h]].searchType&&"or"!==o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"!==o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=encodeURI(l[b+"SearchValue"+h])):l[b+"SearchParams"]+=l[b+"SearchSelectValue"+h].value));("inventory"===b&&l.inventoryFailureFilter||"host"===b&&l.hostFailureFilter)&&(l[b+"SearchParams"]+="&has_active_failures=true"),r&&(l[b+"SearchParams"]+=l[b+"SearchParams"]?"&":"",l[b+"SearchParams"]+="order_by="+encodeURI(r)),l.$emit("doSearch",b,c,d,e)}),l.startSearch=function(a,b){13===a.keyCode&&l.search(b)},l.search=function(a,b,c){c=void 0===c?!0:!1,c&&(l[m]=[]),l.$emit("prepareSearch",a,b,c)},l.sort=function(a){$(".list-header").each(function(){if($(this).attr("id")!==a+"-header"){var b=$(this).find("i");b.attr("class","fa fa-sort")}});var b=$("#"+a+"-header i"),c="";b.hasClass("fa-sort")?(b.removeClass("fa-sort"),b.addClass("fa-sort-up")):b.hasClass("fa-sort-up")?(b.removeClass("fa-sort-up"),b.addClass("fa-sort-down"),c="-"):b.hasClass("fa-sort-down")&&(b.removeClass("fa-sort-down"),b.addClass("fa-sort-up")),r=o.fields[a].searchField?c+o.fields[a].searchField:o.fields[a].sortField?c+o.fields[a].sortField:o.fields[a].sourceModel?c+o.fields[a].sourceModel+"__"+o.fields[a].sourceField:c+a,l.search(o.iterator)},l.searchCleanup=function(){l.removeDoSearch(),l.removePrepareSearch(),l.removePrepareSearch2()}}}]),angular.module("TeamHelper",["RestServices","Utilities","OrganizationListDefinition","SearchHelper","PaginationHelpers","ListGenerator"]).factory("SetTeamListeners",["Alert","Rest",function(a,b){return function(a){var c=a.scope,d=a.set,e=a.iterator;c.$on("TeamResultFound",function(a,b,f){var g,h,i,j;if(f.length===b.length){for(i="organization",j="organization_name",g=0;gSelect existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.",base:"users",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{},fieldActions:{}}),angular.module("CloudCredentialsListDefinition",[]).value("CloudCredentialList",{name:"cloudcredentials",iterator:"cloudcredential",selectTitle:"Add Cloud Credentials",editTitle:"Cloud Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},team:{label:"Team",ngBind:"credential.team_name",sourceModel:"team",sourceField:"name",excludeModal:!0},user:{label:"User",ngBind:"credential.user_username",sourceModel:"user",sourceField:"username",excludeModal:!0}},actions:{add:{mode:"all",ngClick:"addCredential()","class":"btn-sm",awToolTip:"Create a new credential"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash-o",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("CredentialsListDefinition",[]).value("CredentialList",{name:"credentials",iterator:"credential",selectTitle:"Add Credentials",editTitle:"Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},kind:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0}},actions:{add:{mode:"all",ngClick:"addCredential()",awToolTip:"Create a new credential"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("GroupListDefinition",[]).value("GroupList",{name:"groups",iterator:"group",selectTitle:"Copy Groups",editTitle:"Groups",index:!0,well:!1,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{help:{awPopOver:"Choose groups by clicking on each group you wish to add. Click the Select button to add the groups to the selected inventory group.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Adding Groups"}},fieldActions:{edit:{label:"Edit",ngClick:"editGroup(group.id)",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit group",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteGroup(group.id, group.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete group",dataPlacement:"top"}}}),angular.module("HomeGroupListDefinition",[]).value("HomeGroupList",{name:"home_groups",iterator:"group",editTitle:"Groups",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Group",ngClick:"editGroup(group.id, group.inventory)",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-6 ellipsis"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ /#/inventories/' + group.inventory + '/' }}"},source:{label:"Source",searchType:"select",searchOptions:[{name:"ec2",value:"ec2"},{name:"none",value:""},{name:"rax",value:"rax"}],sourceModel:"inventory_source",sourceField:"source",searchOnly:!0},has_external_source:{label:"Has external source?",searchType:"in",searchValue:"ec2,rax",searchOnly:!0,sourceModel:"inventory_source",sourceField:"source"},has_active_failures:{label:"Has failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},last_update_failed:{label:"Update failed?",searchType:"select",searchSingleValue:!0,searchValue:"failed",searchOnly:!0,sourceModel:"inventory_source",sourceField:"status"},id:{label:"ID",searchOnly:!0}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",awToolTip:"{{ group.status_tooltip }}",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",dataPlacement:"top",ngHref:"/#/inventories/{{ group.inventory }}/",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",ngShow:"(group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate(group.id)",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"(group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{label:"Edit",mode:"all",ngClick:"editGroup(group.id)",awToolTip:"Edit group",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HomeHostListDefinition",[]).value("HomeHostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Name",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-7 ellipsis",ngClick:"editHost(host.id, host.name)"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ '/#/inventories/' + host.inventory }}"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Has failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_inventory_sources:{label:"Has external source?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},id:{label:"ID",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{label:"Edit",ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"}},actions:{stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HostListDefinition",[]).value("HostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,well:!1,fields:{name:{key:!0,label:"Host Name",linkTo:"/inventories/{{ inventory_id }}/hosts/{{ host.id }}"},description:{label:"Description"}},actions:{help:{awPopOver:"Select hosts by clicking on each host you wish to add. Add the selected hosts to the group by clicking the Select button.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Selecting Hosts"}},fieldActions:{edit:{label:"Edit",ngClick:"editHost({{ host.id }})",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit host",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete host",dataPlacement:"top"}}}),angular.module("InventoriesListDefinition",[]).value("InventoryList",{name:"inventories",iterator:"inventory",selectTitle:"Add Inventories",editTitle:"Inventories",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},organization:{label:"Organization",ngBind:"inventory.summary_fields.organization.name",linkTo:"/#/organizations/{{ inventory.organization }}",sourceModel:"organization",sourceField:"name",excludeModal:!0},has_inventory_sources:{label:"Cloud sourced?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_active_failures:{label:"Failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},inventory_sources_with_failures:{label:"Sync failures?",searchType:"gtzero",searchValue:"true",searchOnly:!0}},actions:{add:{mode:"all",ngClick:"addInventory()",awToolTip:"Create a new inventory"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{status:{ngHref:"inventory.status_link",iconClass:"{{ 'fa fa-cloud icon-cloud-' + inventory.status_class }}",awToolTip:"{{ inventory.status_tip }}",dataPlacement:"top"},failed_hosts:{ngHref:"inventory.failed_hosts_link",iconClass:"{{ 'fa icon-failures-' + inventory.failed_hosts_class }}",awToolTip:"{{ inventory.failed_hosts_tip }}",dataPlacement:"top"},edit:{label:"Edit",ngClick:"editInventoryProperties(inventory.id)",awToolTip:"Edit inventory",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteInventory(inventory.id, inventory.names')",awToolTip:"Delete inventory",dataPlacement:"top"}}}),angular.module("InventoryGroupsDefinition",[]).value("InventoryGroups",{name:"groups",iterator:"group",editTitle:"{{ inventory_name }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,filterBy:"{ show: true }","class":"table-condensed table-no-border",fields:{name:{label:"Groups",key:!0,ngClick:"showHosts(group.id,group.group_id, false)",ngClass:"group.selected_class",hasChildren:!0,columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",nosort:!0,awDroppable:"{{ group.isDroppable }}",awDraggable:"{{ group.isDraggable }}",dataContainment:"#groups_table",dataTreeId:"{{ group.id }}",dataGroupId:"{{ group.group_id }}",dataType:"group"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createGroup()",awToolTip:"Create a new group"},properties:{mode:"all",awToolTip:"Edit inventory properties",ngClick:"editInventoryProperties()"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refreshGroups()"},stream:{ngClick:"showGroupActivity()",awToolTip:"View Activity Stream",mode:"all"},help:{mode:"all",awToolTip:"Get help building your inventory",ngClick:"showGroupHelp()",id:"inventory-summary-help"}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",ngShow:"group.id > 1",awToolTip:"{{ group.status_tooltip }}",dataTipWatch:"group.launch_tooltip",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",ngShow:"group.id > 1",dataPlacement:"top",ngClick:"showHosts(group.id, group.group_id, group.show_failures)",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",dataTipWatch:"group.launch_tooltip",ngShow:"group.id > 1 && (group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate({{ group.id }})",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"group.id > 1 && (group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{mode:"all",ngClick:"editGroup({{ group.group_id + ',' + group.id }})",awToolTip:"Edit group",ngShow:"group.id > 1",dataPlacement:"top"},"delete":{mode:"all",ngClick:"deleteGroup({{ group.id + ',' + group.group_id }})",awToolTip:"Delete group",ngShow:"group.id != 1",dataPlacement:"top"}}}),angular.module("InventoryHostsDefinition",[]).value("InventoryHosts",{name:"hosts",iterator:"host",editTitle:"{{ selected_group }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,"class":"table-condensed table-no-border",fields:{name:{key:!0,label:"Hosts",ngClick:"editHost(host.id)",searchPlaceholder:"search_place_holder",columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",dataHostId:"{{ host.id }}",dataType:"host",awDraggable:"true"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"},"delete":{ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash",awToolTip:"Delete host",dataPlacement:"top"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createHost()",ngHide:"selected_tree_id == 1",awToolTip:"Create a new host"},stream:{ngClick:"showHostActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("JobEventsListDefinition",[]).value("JobEventList",{name:"jobevents",iterator:"jobevent",editTitle:"Job Events",index:!1,hover:!0,hasChildren:!0,filterBy:"{ show: true }",navigationLinks:{details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",active:!0,icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",icon:"icon-laptop"}},fields:{created:{label:"Created On",columnClass:"col-lg-1 col-md-1 hidden-sm hidden-xs",key:!0,nosort:!0,searchable:!1,link:!1},status:{label:"Status",showValue:!1,columnClass:"col-sm-1 col-xs-2 text-center",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}],nosort:!0,searchable:!1,ngClick:"viewJobEvent({{ jobevent.id }})",awToolTip:"{{ jobevent.statusBadgeToolTip }}",dataPlacement:"top",badgeIcon:"fa icon-job-{{ jobevent.status }}",badgePlacement:"left",badgeToolTip:"{{ jobevent.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgClick:"viewJobEvent({{ jobevent.id }})"},event_display:{label:"Event",hasChildren:!0,ngClick:"toggleChildren(jobevent.id, jobevent.related.children)",nosort:!0,searchable:!1,ngClass:"{{ jobevent.class }}",appendHTML:"jobevent.event_detail"},host:{label:"Host",ngBind:"jobevent.summary_fields.host.name",ngHref:"{{ jobevent.hostLink }}",searchField:"hosts__name",nosort:!0,searchOnly:!1,id:"job-event-host-header","class":"break",columnClass:"col-lg-2 hidden-sm hidden-xs"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{columnClass:"col-sm-1 col-xs-2",view:{label:"View",ngClick:"viewJobEvent(jobevent.id)",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("JobHostDefinition",[]).value("JobHostList",{name:"jobhosts",iterator:"jobhost",editTitle:"All summaries",index:!0,hover:!0,navigationLinks:{ngHide:"host_id !== null",details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",active:!0,icon:"icon-laptop"}},fields:{job:{label:"Job ID",ngClick:"showJob(jobhost.job)",columnShow:"host_id !== null",key:!0,desc:!0},host:{label:"Host",key:!0,sourceModel:"host",sourceField:"name",ngBind:"jobhost.host_name",ngHref:"jobhost.hostLinkTo"},status:{label:"Status",badgeNgHref:"{{ jobhost.statusLinkTo }}",badgeIcon:"fa icon-job-{{ jobhost.status }}",badgePlacement:"left",badgeToolTip:"{{ jobhost.statusBadgeToolTip }}",badgeTipPlacement:"top",ngHref:"{{ jobhost.statusLinkTo }}",awToolTip:"{{ jobhost.statusBadgeToolTip }}",dataPlacement:"top",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}]},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},ok:{label:"Success",searchable:!1},changed:{label:"Changed",searchable:!1},failures:{label:"Failure",searchable:!0,searchLabel:"Contains failed events?",searchType:"gtzero"},dark:{label:"Unreachable",searchable:!0,searchType:"gtzero",searchLabel:"Contains unreachable hosts?"},skipped:{label:"Skipped",searchable:!1}},actions:{help:{awPopOver:"
\n
Success
Tasks successfully executed on the host.
\n
Changed
Actions taken on the host.
\n
Failure
Tasks that failed on the host.
\n
Unreachable
Times the ansible server could not reach the host.
\n
Skipped
Tasks bypassed and not performed on the host due to prior task failure or the host being unreachable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Job Host Summary",id:"jobhost-help-button"},refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refresh()",ngShow:"host_id == null"}},fieldActions:{}}),angular.module("JobTemplatesListDefinition",[]).value("JobTemplateList",{name:"job_templates",iterator:"job_template",selectTitle:"Add Job Template",editTitle:"Job Templates",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addJobTemplate()",basePaths:["job_templates"],awToolTip:"Create a new template"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editJobTemplate(job_template.id)",icon:"icon-edit",awToolTip:"Edit template","class":"btn-default btn-xs",dataPlacement:"top"},submit:{label:"Launch",icon:"icon-rocket",mode:"all","class":"btn-xs btn-success",ngClick:"submitJob(job_template.id)",awToolTip:"Start a job using this template",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteJobTemplate(job_template.id, job_template.name)",icon:"icon-trash","class":"btn-danger btn-xs",awToolTip:"Delete template",dataPlacement:"top"}}}),angular.module("JobsListDefinition",[]).value("JobList",{name:"jobs",iterator:"job",editTitle:"Jobs",index:!1,hover:!0,"class":"jobs-table",fields:{id:{label:"Job ID",key:!0,desc:!0,searchType:"int"},inventory:{label:"Inventory ID",searchType:"int",searchOnly:!0},created:{label:"Create On",link:!1,searchable:!1},job_template:{label:"Job Template",ngBind:"job.summary_fields.job_template.name",ngHref:"{{ '/#/job_templates/' + job.job_template }}",sourceModel:"job_template",sourceField:"name"},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},status:{label:"Status","class":"job-{{ job.status }}",searchType:"select",linkTo:"{{ job.statusLinkTo }}",searchOptions:[{name:"new",value:"new"},{name:"waiting",value:"waiting"},{name:"pending",value:"pending"},{name:"running",value:"running"},{name:"successful",value:"successful"},{name:"error",value:"error"},{name:"failed",value:"failed"},{name:"canceled",value:"canceled"}],badgeIcon:"fa icon-job-{{ job.status }}",badgePlacement:"left",badgeToolTip:"{{ job.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgHref:"{{ job.statusLinkTo }}",awToolTip:"{{ job.statusBadgeToolTip }}",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{submit:{label:"Relaunch",icon:"icon-rocket",mode:"all",ngClick:"submitJob(job.id, job.summary_fields.job_template.name)",awToolTip:"Start the job",dataPlacement:"top"},cancel:{label:"Stop",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Cancel a running or pending job",ngShow:"job.status == 'pending' || job.status == 'running' || job.status == 'waiting'",dataPlacement:"top"},"delete":{label:"Delete",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Delete the job",ngShow:"job.status != 'pending' && job.status != 'running' && job.status != 'waiting'",dataPlacement:"top"},dropdown:{type:"DropDown",label:"View",icon:"fa-search-plus","class":"btn-default btn-xs",options:[{ngClick:"editJob(job.id, job.summary_fields.job_template.name)",label:"Status"},{ngClick:"viewEvents(job.id, job.summary_fields.job_template.name)",label:"Events",ngHide:"job.status == 'new'"},{ngClick:"viewSummary(job.id, job.summary_fields.job_template.name)",label:"Host Summary",ngHide:"job.status == 'new'"}]}}}),angular.module("OrganizationListDefinition",[]).value("OrganizationList",{name:"organizations",iterator:"organization",selectTitle:"Add Organizations",editTitle:"Organizations",hover:!0,index:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addOrganization()",awToolTip:"Create a new organization"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editOrganization(organization.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit organization",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteOrganization(organization.id, organization.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete organization",dataPlacement:"top"}}}),angular.module("PermissionListDefinition",[]).value("PermissionList",{name:"permissions",iterator:"permission",selectTitle:"Add Permission",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',editTitle:"Permissions",index:!0,well:!0,fields:{name:{key:!0,label:"Name",ngClick:"editPermission(permission.id)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},actions:{add:{mode:"all",ngClick:"addPermission()",awToolTip:"Add a new permission",ngShow:"PermissionAddAllowed"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editPermission(permission.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit permission",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deletePermission(permission.id, permission.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete permission",ngShow:"PermissionAddAllowed",dataPlacement:"top"}}}),angular.module("ProjectsListDefinition",[]).value("ProjectList",{name:"projects",iterator:"project",selectTitle:"Add Project",editTitle:"Projects",selectInstructions:"
Select existing projects by clicking each project or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new project by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",columnClass:"hidden-sm hidden-xs",excludeModal:!0},scm_type:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0},status:{label:"Status",ngClick:"showSCMStatus(project.id)",awToolTip:"View details of last SCM Update",dataPlacement:"top",badgeIcon:"{{ 'fa icon-failures-' + project.badge }}",badgePlacement:"left",searchType:"select",searchOptions:[],excludeModal:!0},last_updated:{label:"Last Updated",type:"date",excludeModal:!0,searchable:!1}},actions:{add:{mode:"all",ngClick:"addProject()",awToolTip:"Create a new project"},help:{awPopOver:"
\n
Updating
A source control update is in progress.
\n
Never Updated
This project has not yet been updated from source control.
\n
Failed
An error occurred during the most recent source control update, click the status text for more information.
\n
Successful
TThe latest source control update completed successfully.
\n
Missing
The previously configured local project directory is missing.
\n
N/A
The project is not linked to source control, so updates are not applicable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all",awToolTip:"Click for help",awTipPlacement:"top"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editProject(project.id)",awToolTip:"Edit project properties",dataPlacement:"top"},scm_update:{label:"Update",ngClick:"SCMUpdate(project.id)",awToolTip:"{{ project.scm_update_tooltip }}",ngClass:"project.scm_type_class",dataPlacement:"top"},cancel:{label:"Stop",ngClick:"cancelUpdate(project.id, project.name)",awToolTip:"Cancel a running SCM update process",ngShow:"project.status == 'updating'",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteProject(project.id, project.name)",awToolTip:"Permanently remove project from the database",ngShow:"project.status !== 'updating'",dataPlacement:"top"}}}),angular.module("StreamListDefinition",[]).value("StreamList",{name:"activities",iterator:"activity",editTitle:"Activity Stream",selectInstructions:"",index:!1,hover:!0,"class":"table-condensed",searchWidgets:3,fields:{timestamp:{label:"Event Time",key:!0,desc:!0,noLink:!0,searchable:!1},user:{label:"Initiated by",ngBindHtml:"activity.user",sourceModel:"actor",sourceField:"username",searchPlaceholder:"Username",searchWidget:1},description:{label:"Action",ngBindHtml:"activity.description",nosort:!0,searchable:!1,columnClass:"col-lg-7"},system_event:{label:"System event",searchOnly:!0,searchType:"isnull",sourceModel:"actor",sourceField:"username",searchWidget:1},all_objects:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All resources",searchWidget:2},credential_search:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Credential name",searchWidget:2,searchField:"object1"},group_search:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Group name",searchWidget:2,searchField:"object1"},host_search:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Host name",searchWidget:2,searchField:"object1"},inventory_search:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Inventory name",searchWidget:2,searchField:"object1"},job_template_search:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Job template name",searchWidget:2,searchField:"object1"},job_search:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:2,searchField:"object1"},organization_search:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Organization name",searchWidget:2,searchField:"object1"},project_search:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Project name",searchWidget:2,searchField:"object1"},user_search:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Primary username",searchWidget:2,searchField:"object1"},all_objects3:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All related resources",searchWidget:3,searchField:"object2"},credential_search3:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Related credential name",searchWidget:3,searchField:"object2"},group_search3:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Related group name",searchWidget:3,searchField:"object2"},host_search3:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Related host name",searchWidget:3,searchField:"object2"},inventory_search3:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Related inventory name",searchWidget:3,searchField:"object2"},job_search3:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:3,searchField:"object2"},job_template_search3:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Related job template name",searchWidget:3,searchField:"object2"},organization_search3:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Related organization name",searchWidget:3,searchField:"object2"},project_search3:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Related project name",searchWidget:3,searchField:"object2"},user_search3:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Related username",searchWidget:3,searchField:"object2"}},actions:{refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refreshStream()"},close:{mode:"all",awToolTip:"Close Activity Stream view",ngClick:"closeStream()"}},fieldActions:{view:{label:"View",ngClick:"showDetail(activity.id)",icon:"fa-zoom-in","class":"btn-default btn-xs",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("TeamsListDefinition",[]).value("TeamList",{name:"teams",iterator:"team",selectTitle:"Add Team",editTitle:"Teams",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"},organization:{label:"Organization",ngBind:"team.organization_name",sourceModel:"organization",sourceField:"name"}},actions:{add:{mode:"all",ngClick:"addTeam()",awToolTip:"Create a new team"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editTeam(team.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit team",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteTeam(team.id, team.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete team",dataPlacement:"top"}}}),angular.module("UserListDefinition",[]).value("UserList",{name:"users",iterator:"user",selectTitle:"Add Users",editTitle:"Users",selectInstructions:"
Select existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.
When available, a brand new user can be created by clicking the green Create New button.
",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{add:{label:"Create New",mode:"all",ngClick:"addUser()",basePaths:["organizations","users"],"class":"btn-xs",awToolTip:"Create a new user"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editUser(user.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit user",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteUser(user.id, user.username)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete user",dataPlacement:"top"}}}),angular.module("InventorySyncStatusWidget",["RestServices","Utilities"]).factory("InventorySyncStatus",["$rootScope","$compile",function(a,b){return function(a){function c(a){var b=a.label,c=a.count,d=a.fail,e=a.link,f=a.fail_link,g="
\n",d+="\n",d+="\n",d+=c({label:"Inventories",count:k.inventories&&k.inventories.total_with_inventory_source?k.inventories.total_with_inventory_source:0,fail:k.inventories&&k.inventories.inventory_failed?k.inventories.inventory_failed:0,link:"/#/inventories/?has_inventory_sources=true",fail_link:"/#/inventories/?inventory_sources_with_failures=true"}),e=0,f=0,k.inventory_sources)for(h in k.inventory_sources)e+=k.inventory_sources[h].total?k.inventory_sources[h].total:0,f+=k.inventory_sources[h].failed?k.inventory_sources[h].failed:0;d+=c({label:"Groups",count:e,fail:f,link:"/#/home/groups/?has_external_source=true",fail_link:"/#/home/groups/?status=failed"});for(h in k.inventory_sources)k.inventory_sources[h].total&&(d+=c({label:k.inventory_sources[h].label,count:k.inventory_sources[h].total?k.inventory_sources[h].total:0,fail:k.inventory_sources[h].failed?k.inventory_sources[h].failed:0,link:"/#/home/groups/?source="+h,fail_link:"/#/home/groups/?status=failed&source="+h}));d+="\n",d+="
\n",e+="\n",e+="\n",f=0,l.scm_types)for(h in l.scm_types)f+=l.scm_types[h].total?l.scm_types[h].total:0;e+=c({label:"Projects",link:"/#/projects",count:f,fail:l.projects&&l.projects.failed?l.projects.failed:0,fail_link:"/#/projects/?status=failed"}),i=[];for(h in l.scm_types)i.push(h);for(i.sort(),d=0;d\n",e+="
\n",e+="
\n",e+="
\n",e+="\n",g=angular.element(document.getElementById(k)),g.html(e),b(g)(j),j.$emit("WidgetLoaded")}}]),angular.module("StreamWidget",["RestServices","Utilities","StreamListDefinition","SearchHelper","PaginationHelpers","RefreshHelper","ListGenerator","StreamWidget","AuthService"]).factory("setStreamHeight",[function(){return function(){var a=$("#stream-content").height(),b=parseInt($("#tab-content-container").css("min-height").replace(/px/,"")),c=a>b?a:b;$("#tab-content-container").css({"min-height":c})}}]).factory("ShowStream",["setStreamHeight","Authorization",function(a){return function(){var b=$("#stream-container");b.css({position:"absolute",top:0,left:0,width:"100%","min-height":"100%","background-color":"#FFF"}),a(),b.show("slide",{direction:"left"},{duration:500,queue:!1})}}]).factory("HideStream",["LoadBreadCrumbs",function(a){return function(){var b=$("#stream-container");b.hide("slide",{direction:"left"},{duration:500,queue:!1}),setTimeout(function(){b.detach(),b.empty(),b.unbind(),$("#tab-content-container").css({"min-height":0})},500),a()}}]).factory("StreamBreadCrumbs",["$rootScope","$location",function(a,b){return function(){a.breadcrumbs=[];var c,d,e,f,g=b.path().split("/");for(g.splice(0,1),e=0;e=f;f++)c+="/"+g[f];for(f=0;f0)for(f=0;e>=f;f++)c+="/"+g[f];else c="/"+g[e];d=g[e],d=d.charAt(0).toUpperCase()+d.slice(1)}a.breadcrumbs.push({path:c,title:d,ngClick:"closeStream('"+c+"')"})}}}]).factory("FixUrl",[function(){return function(a){return a.replace(/\/api\/v1\//,"/#/")}}]).factory("BuildUrl",[function(){return function(a){var b="/#/";switch(a.base){case"group":case"host":b+="home/"+a.base+"s/?id="+a.id;break;case"inventory":b+="inventories/"+a.id+"/";break;default:b+=a.base+"s/"+a.id+"/"}return b}}]).factory("BuildDescription",["FixUrl","BuildUrl",function(a,b){return function(a){function c(a){return a.replace(/^_deleted_\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d+\+\d+:\d+_/,"")}var d,e,f,g,h,i,j,k;d=a.operation,d+=/e$/.test(a.operation)?"d ":"ed ",e=d,f=a.object1,g=a.object2,h=a.summary_fields[f]?a.summary_fields[f][0]:null,i=f===g?a.summary_fields[f][1]:a.summary_fields[g]?a.summary_fields[g][0]:null,("user"===f||"user"===g)&&(a.summary_fields.user[0].name=a.summary_fields.user[0].username),i&&i.name&&!/^_delete/.test(i.name)?(i.base=g,d+=g+' '+i.name+""+("disassociate"===a.operation?" from ":" to "),e+=g+" "+i.name+("disassociate"===a.operation?" from ":" to ")):g&&(j="",i&&i.name&&(j=" "+c(i.name)),d+=g+j+("disassociate"===a.operation?" from ":" to "),e+=g+j+("disassociate"===a.operation?" from ":" to ")),h&&h.name&&!/^\_delete/.test(h.name)?(h.base=f,d+=f+' '+h.name+"",e+=f+" "+h.name):f&&(j="",k="",!h||!h.name||h&&h.name&&/^_delete/.test(h.name)?a.changes&&a.changes.name?"string"==typeof a.changes.name?(j=" "+a.changes.name,k=j):"object"==typeof a.changes.name&&Array.isArray(a.changes.name)&&(j=" "+a.changes.name[0],k=j):"job"===f&&h&&a.changes&&a.changes.job_template?"delete"!==a.operation?(h.base=f,j=' '+h.id+" "+a.changes.job_template+"",k=" "+h.id+" "+a.changes.job_template):(j=" "+h.id+" "+a.changes.job_template,k=j):"job"===f&&h&&("delete"!==a.operation?(h.base=f,j=' '+h.id+"",k=" "+h.id):(j=" "+h.id,k=j)):h&&h.name&&(j=" "+c(h.name),k=j),d+=f+j,e+=f+k),a.description=d,a.description_nolink=e}}]).factory("ShowDetail",["$rootScope","Rest","Alert","GenerateForm","ProcessErrors","GetBasePath","FormatDate","ActivityDetailForm","Empty","Find",function(a,b,c,d,e,f,g,h,i,j){return function(a){var b,c,e,f=a.activity_id,i=a.scope,k=d,l=h,m=j({list:i.activities,key:"id",val:f});m&&(m.changes_stringified=JSON.stringify(m.changes,null," "),b=m.changes_stringified.match(/\n/g),c=b?b.length:1,c=1>c?3:10,l.fields.changes.rows=10,e=k.inject(l,{mode:"edit",modal:!0,related:!1}),e.changes=m.changes_stringified,e.user=(m.summary_fields.actor?m.summary_fields.actor.username:"system")+" on "+g(new Date(m.timestamps)),e.operation=m.description_nolink,e.formModalAction=function(){$("#form-modal").modal("hide")},$("#form-modal").on("show.bs.modal",function(){$("#form-modal-body").css({width:"auto",height:"auto","max-height":"100%"})}),e.formModalActionLabel="OK",e.formModalCancelShow=!1,e.formModalInfo=!1,e.formModalHeader="Event "+m.id,e.$$phase||e.$digest())}}]).factory("Stream",["$rootScope","$location","Rest","GetBasePath","ProcessErrors","Wait","StreamList","SearchInit","PaginateInit","GenerateList","FormatDate","ShowStream","HideStream","BuildDescription","FixUrl","BuildUrl","ShowDetail","StreamBreadCrumbs","setStreamHeight","Find","Store",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){return function(c){var e,f,o,v,w=g,x=d("activity_stream"),y=j,z=b.path().replace(/^\//,"").split("/")[0],A=c.scope,B=u("CurrentSearchParams"),C=c&&c.inventory_name?c.inventory_name:null,D=c&&c.url?c.url:null;a.flashMessage=null,D?x=D:"/home"!==b.path()&&(e="inventories"===z?"inventory":z.replace(/s$/,""),f=b.path().split("/"),f.splice(0,1),f.length>1&&/^\d+/.test(f[f.length-1])?(e=f[f.length-2],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?"+e+"__id="+f[f.length-1]):f.length>1?(e=f[f.length-1],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?or__object1="+e+"&or__object2="+e):x+="?or__object1="+e+"&or__object2="+e),$("#tab-content-container").append('
'),r(),C&&(o=t({list:a.breadcrumbs,key:"title",val:"{{ inventory_name }}"}),o&&(o.title=C)),l(),v=y.inject(w,{mode:"edit",id:"stream-content",searchSize:"col-lg-3",secondWidget:!0,activityStream:!0}),v.streamTitle=c&&c.title?c.title:null,v.closeStream=function(a){m(),v.searchCleanup&&v.searchCleanup(),B&&h({scope:A,set:B.set,list:B.list,url:B.defaultUrl,iterator:B.iterator,sort_order:B.sort_order,setWidgets:!1}),a&&b.path(a)},v.refreshStream=function(){v.search(w.iterator)},v.showDetail=function(a){q({scope:v,activity_id:a})},v.removeStreamPostRefresh&&v.removeStreamPostRefresh(),v.removeStreamPostRefresh=v.$on("PostRefresh",function(){var a,b,c,d,e,f;for(a=0;a'+v.activities[a].summary_fields.actor.username+"":"system",d=/^\_delete/,e=v.activities[a].object1,f=v.activities[a].object2,e&&v.activities[a].summary_fields[e]&&v.activities[a].summary_fields[e].name?d.test(v.activities[a].summary_fields[e].name)?v.activities[a].objects=v.activities[a].summary_fields[e].name:(c=p(v.activities[a].summary_fields.object1),v.activities[a].objects=''+v.activities[a].summary_fields[e].name+""):v.activities[a].object1&&(v.activities[a].objects=v.activities[a].object1),f&&v.activities[a].summary_fields[f]&&v.activities[a].summary_fields[f].name?d.test(v.activities[a].summary_fields.object2.name)?v.activities[a].objects+=","+v.activities[a].summary_fields[f].name:(c=p(v.activities[a].summary_fields.object2),v.activities[a].objects+=', '+v.activities[a].summary_fields[f].name+""):v.activities[a].object2&&(v.activities[a].objects+=", "+v.activities[a].object2),n(v.activities[a]);setTimeout(function(){s()},500)}),h({scope:v,set:w.name,list:w,url:x}),i({scope:v,list:w,url:x}),v.search(w.iterator)}}]),angular.module("AuthService",["ngCookies","Utilities"]).factory("Authorization",["$http","$rootScope","$location","$cookieStore","GetBasePath",function(a,b,c,d,e){return{setToken:function(a,c){d.remove("token"),d.remove("token_expires"),d.remove("userLoggedIn"),d.put("token",a),d.put("token_expires",c),d.put("userLoggedIn",!0),d.put("sessionExpired",!1),b.token=a,b.userLoggedIn=!0,b.token_expires=c,b.sessionExpired=!1},isUserLoggedIn:function(){return void 0===b.userLoggedIn&&(b.userLoggedIn=d.get("userLoggedIn"),b.sessionExpired=d.get("sessionExpired")),b.userLoggedIn},getToken:function(){return b.token?b.token:d.get("token")},retrieveToken:function(b,c){return a({method:"POST",url:e("authtoken"),data:{username:b,password:c}})},logout:function(){var a=angular.element(document.getElementById("main-view")).scope();a.$destroy(),b.$destroy(),d.remove("accordions"),d.remove("token"),d.remove("token_expires"),d.remove("current_user"),d.remove("lastPath"),d.put("userLoggedIn",!1),d.put("sessionExpired",!1),d.remove("lastPath","/home"),b.current_user={},b.license_tested=void 0,b.userLoggedIn=!1,b.sessionExpired=!1,b.token=null,b.token_expires=null,b.lastPath="/home"},getLicense:function(){return a({method:"GET",url:e("config"),headers:{Authorization:"Token "+this.getToken()}})},setLicense:function(a){a.tested=!1,d.put("license",a)},licenseTested:function(){var a,c;return void 0!==b.license_tested?c=b.license_tested:(a=d.get("license"),c=a&&void 0!==a.tested?a.tested:!1),c},getUser:function(){return a({method:"GET",url:"/api/v1/me/",headers:{Authorization:"Token "+this.getToken()}})},setUserInfo:function(a){b.current_user=a.results[0],d.put("current_user",a.results[0])},restoreUserInfo:function(){b.current_user=d.get("current_user")},getUserInfo:function(a){var c;return b.current_user?b.current_user[a]:(this.restoreUserInfo(),c=d.get("current_user"),c[a])}}}]),angular.module("InventoryTree",["Utilities","RestServices","GroupsHelper","PromptDialog"]).factory("SortNodes",[function(){return function(a){var b,c,d=[],e=[];for(b=0;b0?!0:!1,has_inventory_sources:s[e].has_inventory_sources,id:r,source:s[e].summary_fields.inventory_source.source,group_id:s[e].id,event_level:c,children:i,ngicon:s[e].children.length>0?"fa fa-minus-square-o node-toggle":"fa fa-square-o node-no-toggle",ngclick:"toggle("+r+")",related:{children:s[e].children.length>0?s[e].related.children:"",inventory_source:s[e].related.inventory_source},status:s[e].summary_fields.inventory_source.status,status_class:k["class"],status_tooltip:k.tooltip,launch_tooltip:k.launch_tip,launch_class:k.launch_class,hosts_status_tip:n.tooltip,show_failures:n.failures,hosts_status_class:n["class"],selected_class:"",show:!0,isDraggable:!0,isDroppable:!0},q.push(o),p&&o.group_id===p&&(m.selected_tree_id=r,m.selected_group_id=o.group_id),s[e].children.length>0&&j(s[e].children,r,c+1)}}function k(){e("start"),a.setUrl(b("inventory")+l+"/"),a.get().success(function(a){m.$emit("buildAllGroups",a.name,a.related.tree,a.related.groups)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+l+". GET returned: "+b})})}var l=h.inventory_id,m=h.scope,n=h.refresh,o=h.emit,p=h.new_group_id,q=[],r=1;m.buildAllGroupsRemove&&m.buildAllGroupsRemove(),m.buildAllGroupsRemove=m.$on("buildAllGroups",function(b,d,f){a.setUrl(f),a.get().success(function(a){i(a),j(a,0,0),m.autoShowGroupHelp=0===a.length?!0:!1,n?(m.groups=q,m.$emit("GroupTreeRefreshed",d,q,o)):m.$emit("GroupTreeLoaded",d,q,o)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory tree for: "+l+". GET returned: "+b})})}),k()}}]).factory("UpdateGroup",["ApplyEllipsis","GetSyncStatusMsg","Empty",function(a,b,c){return function(d){var e,f,g,h,i,j=d.scope,k=d.group_id,l=d.properties;for(e=0;e\n',m+='
\n',m+='
\n',m+='
\n',m+='\n',m+=1===k.id||0===l.parent?"
Move Group
\n":"
Copy or Move?
\n",m+="
\n",m+='
\n',1===k.id?m+="
Are you sure you want to move group "+l.name+" to the top level?
":0===l.parent?m+="
Are you sure you want to move group "+l.name+" from the top level and make it a child of "+k.name+"?
":(m+='
\n',m+="
Would you like to copy or move group "+l.name+" to group "+k.name+"?
\n",m+="\n",i=angular.element(document.getElementById("inventory-modal-container")),i.empty().append(m),a(i)(j),$("#copy-prompt-modal").modal({backdrop:"static",keyboard:!0,show:!0}),j.moveGroup=function(){var a,b,i;$("#copy-prompt-modal").modal("hide"),e("start"),j.removeGroupRemove&&j.removeGroupRemove(),j.removeGroupRemove=j.$on("removeGroup",function(){l.parent>0?(i=d({list:j.groups,key:"id",val:l.parent}),a=h("base")+"groups/"+i.group_id+"/children/",f.setUrl(a),f.post({id:l.group_id,disassociate:1}).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to remove "+l.name+" from "+i.name+". POST returned status: "+b})})):j.$emit("GroupDeleteCompleted")}),a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id},f.setUrl(a),f.post(b).success(function(){j.$emit("removeGroup")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})},j.copyGroup=function(){$("#copy-prompt-modal").modal("hide"),e("start");var a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id};f.setUrl(a),f.post(b).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})}}}]).factory("CopyMoveHost",["$compile","Alert","ProcessErrors","Find","Wait","Rest","Empty","GetBasePath",function(a,b,c,d,e,f,g,h){return function(b){var g,i,j=b.scope,k=d({list:j.groups,key:"id",val:b.target_tree_id}),l=d({list:j.hosts,key:"id",val:b.host_id}),m=!1,n="";if(l.summary_fields.all_groups)for(i=0;i\n',n+='
URL must begin with ssh, http or https and may not contain '@'
\n"),p+='\n',b.chkPass&&(p+='
Password must be stronger
\n',p+='
\n',p+='
\n',p+='\n',p+="
\n",p+=k({hdr:"Password Complexity",content:'
A password with reasonable strength is required. As you type the password a progress bar will measure the strength. Sufficient strength is reached when the bar turns green.
Password strength is judged using the following:
Minimum 8 characters in length
\n
Contains a sufficient combination of the following items:\n
\n';for(b in this.form.actions)("all"===this.form.actions[b].mode||this.form.actions[b].mode===a.mode)&&(c+=this.button({btn:this.form.actions[b],action:b,toolbar:!0}));return c+="
\n");for(d in this.form.buttons)"object"==typeof this.form.buttons[d]&&(e=this.form.buttons[d],"save"===d&&(e.label="Save",e["class"]="btn-success"),"reset"===d&&(e.label="Reset",e["class"]="btn-default"),p+='\n");p+="
\n"),j=1,k=m.related[g].base?m.related[g].base:g,k=k.replace(/^\//,"");for(d in m.related[g].fields)j++,n+=i({list:m.related[g],fld:d,options:a,base:k});n+='
\n';for(b in f.fields)void 0!==f.fields[b].searchable&&f.fields[b].searchable!==!0||(void 0!==f.fields[b].searchWidget&&1!==f.fields[b].searchWidget||1!==c)&&f.fields[b].searchWidget!==c||(h+='
\n';
+for(j in t.actions)("all"===t.actions[j].mode||t.actions[j].mode===b.mode)&&(void 0===t.actions[j].basePaths||t.actions[j].basePaths&&t.actions[j].basePaths.indexOf(c)>-1)&&(s+=this.button({btn:t.actions[j],action:j,toolbar:!0}));"select"===b.mode&&t.selectInstructions&&(k={awPopOver:t.selectInstructions,dataPlacement:"top",dataContainer:"body","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Help",iconSize:"fa-lg"},s+=this.button({btn:k,action:"help",toolbar:!0})),s+="
\n');for(n in t.fields)void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+='
\n"),o=2,c=t.base?t.base:t.name,c=c.replace(/^\//,"");for(n in t.fields)o++,void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+=h({list:t,fld:n,options:b,base:c}));if("select"===b.mode||"lookup"===b.mode)s+='
\n"),"groups"!==t.name&&(s+=e("lookup"===b.mode||b.id&&"form-modal-body"===b.id?{set:t.name,iterator:t.iterator}:{set:t.name,iterator:t.iterator})),s}}}]),angular.module("PromptDialog",["Utilities"]).factory("Prompt",[function(){return function(a){var b,c=angular.element(document.getElementById("prompt-modal")),d=c.scope();d.promptHeader=a.hdr,d.promptBody=a.body,d.promptAction=a.action,b=null===a["class"]||void 0===a["class"]?"btn-danger":a["class"],$("#prompt_action_btn").removeClass(b).addClass(b),$(c).modal({backdrop:"static",keyboard:!0,show:!0})}}]),String.prototype.strReverse=function(){var a,b="";for(a=0;aA credential must be associated with either a user or a team. Choosing a user allows only the selected user access to the credential. Choosing a team shares the credential with all team members.",dataTitle:"Owner",dataPlacement:"right",dataContainer:"body"},user:{label:"User that owns this credential",type:"lookup",sourceModel:"user",sourceField:"username",ngClick:"lookUpUser()",ngShow:"owner == 'user'",awRequiredWhen:{variable:"user_required",init:"false"}},team:{label:"Team that owns this credential",type:"lookup",sourceModel:"team",sourceField:"name",ngClick:"lookUpTeam()",ngShow:"owner == 'team'",awRequiredWhen:{variable:"team_required",init:"false"}},kind:{label:"Type",excludeModal:!0,type:"select",ngOptions:"kind.label for kind in credential_kind_options",ngChange:"kindChange()",addRequired:!0,editRequired:!0,helpCollapse:[{hdr:"Select a Credential Type",content:"
\n
AWS
\n
Access keys for Amazon Web Services used for inventory management or deployment.
\n
Machine
\n
Authentication for remote machine access. This can include SSH keys, usernames, passwords, and sudo information. Machine credentials are used when submitting jobs to run playbooks against remote hosts.
Rackspace
\n
Access information for Rackspace Cloud used for inventory management or deployment.
\n
SCM
\n
Used to check out and synchronize playbook repositories with a remote source control management system such as Git, Subversion (svn), or Mercurial (hg). These credentials are used on the Projects tab.
Click on the regions field to see a list of regions for your cloud provider. You can select multiple regions, or choose All to include all regions. Tower will only be updated with Hosts associated with the selected regions.
Override variables found in ec2.ini and used by the inventory update script. For a detailed description of these variables view ec2.ini in the Ansible github repo.
Enter variables using either JSON or YAML syntax. Use the radio button to toggle between the two.
If checked, all variables for child groups and hosts will be removed and replaced by those found on the external source.
When not checked a merge will be performed, combining local variables with those found on the external source.
",dataTitle:"Overwrite Variables",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"update_on_launch",label:"Update on Launch",type:"checkbox",ngShow:"source.value !== '' && source.value !== null",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this inventory, refresh the inventory from the selected source before executing job tasks.
",dataTitle:"Update on Launch",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{labelClass:"col-lg-3",controlClass:"col-lg-5",save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("HostGroupsFormDefinition",[]).value("HostGroupsForm",{editTitle:"Host Groups",name:"host",well:!1,formLabelSize:"col-lg-3",formFieldSize:"col-lg-9",fields:{groups:{label:"Groups",type:"select",multiple:!0,ngOptions:"group.name for group in inventory_groups",addRequired:!0,editRequired:!0,awPopOver:"
Provide a host name, ip address, or ip address:port. Examples include:
',dataTitle:"Inventory Variables",dataPlacement:"right",dataContainer:"body"}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("JobEventDataDefinition",[]).value("JobEventDataForm",{editTitle:"{{ id }} - {{ event_display }}",name:"job_events",well:!1,"class":"horizontal-narrow",fields:{event_data:{label:!1,type:"textarea",readonly:!0,rows:18,"class":"modal-input-xxlarge"}}}),angular.module("JobEventsFormDefinition",[]).value("JobEventsForm",{name:"job_events",well:!1,forceListeners:!0,fields:{status:{labelClass:"job-{{ status }}",type:"custom",section:"Event",control:'
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",awRequiredWhen:{variable:"playbookrequired",init:"true"},column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
The number of parallel or simultaneous processes to use while executing the playbook. 0 signifies the default value from the ansible configuration file.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
',dataTitle:"Limit",dataPlacement:"right",dataContainer:"body"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting the Tower server using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",addRequired:!0,editRequired:!0,column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
For more information and examples see the Selecting Targets section under Inventory and Patterns in the Ansible documentation.
',dataContainer:"body",dataTitle:"Limit",dataPlacement:"right"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting Tower using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
A project must have at least one organization. Pick one organization now to create the project, and then after the project is created you can add additional organizations.
Only super users and organization administrators are allowed to make changes to projects. Associating one or more organizations to a project determins which organizations admins have access to modify the project.",dataTitle:"Organization",dataContainer:"body",dataPlacement:"right"},scm_type:{label:"SCM Type",type:"select",ngOptions:"type.label for type in scm_type_options",ngChange:"scmChange()",addRequired:!0,editRequired:!0},missing_path_alert:{type:"alertblock","class":"alert-info",ngShow:"showMissingPlaybooksAlert && scm_type.value == ''",alertTxt:'
WARNING: There are no unassigned playbook directories in the base project path {{ base_dir }}. Either the projects directory is empty, or all of the contents are already assigned to other projects. New projects can be checked out from source control by changing the SCM type option rather than specifying checkout paths manually. To continue with manual setup, log into the Tower host and ensure content is present in a subdirectory under {{ base_dir }}. Run "chown -R awx" on the content directory to ensure Tower can read the playbooks.
',closeable:!1},base_dir:{label:"Project Base Path",type:"textarea",showonly:!0,ngShow:"scm_type.value == ''",awPopOver:"
Base path used for locating playbooks. Directories found inside this path will be listed in the playbook directory drop-down. Together the base path and selected playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
",dataTitle:"Project Base Path",dataContainer:"body",dataPlacement:"right"},local_path:{label:"Playbook Directory",type:"select",id:"local-path-select",ngOptions:"path.label for path in project_local_paths",awRequiredWhen:{variable:"pathRequired",init:!1},ngShow:"scm_type.value == '' && !showMissingPlaybooksAlert",awPopOver:"
Select from the list of directories found in the base path.Together the base path and the playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
Note: If using SSH protocol for GitHub or Bitbucket, enter in the SSH key only, do not enter a username (other than git). Additionally, GitHub and Bitbucket do not support password authentication when using SSH protocol. GIT read only protocol (git://) does not use username or password information.',show:"scm_type.value == 'git'"},{hdr:"SVN URLs",content:'
Note: Mercurial does not support password authentication for SSH. If applicable, add the username, password and key below. Do not put the username and key in the URL. If using Bitbucket and SSH, do not supply your Bitbucket username.',show:"scm_type.value == 'hg'"}]},scm_branch:{labelBind:"scmBranchLabel",type:"text",ngShow:"scm_type && scm_type.value !== ''",addRequired:!1,editRequired:!1},credential:{label:"SCM Credential",type:"lookup",ngShow:"scm_type && scm_type.value !== ''",sourceModel:"credential",sourceField:"name",ngClick:"lookUpCredential()",addRequired:!1,editRequired:!1},checkbox_group:{label:"SCM Update Options",type:"checkbox_group",ngShow:"scm_type && scm_type.value !== ''",fields:[{name:"scm_clean",label:"Clean",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Remove any local modifications prior to performing an update.
",dataTitle:"SCM Clean",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_delete_on_update",label:"Delete on Update",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Delete the local repository in its entirety prior to performing an update.
Depending on the size of the repository this may significantly increase the amount of time required to complete an update.
",dataTitle:"SCM Delete",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_update_on_launch",label:"Update on Launch",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this project, perform an update to the local repository prior to starting the job.
",dataTitle:"SCM Update",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{add:{ngClick:"add('organizations')",icon:"icon-plus",label:"Add",awToolTip:"Add an organization"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('organizations', organization.id, organization.name)",icon:"icon-edit",awToolTip:"Edit the organization","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('organizations', organization.id, organization.name, 'organizations')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the organization"}}}}}),angular.module("TeamFormDefinition",[]).value("TeamForm",{addTitle:"Create Team",editTitle:"{{ name }}",name:"team",well:!0,collapse:!0,collapseTitle:"Team Settings",collapseMode:"edit",collapseOpen:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{name:{label:"Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!1},description:{label:"Description",type:"text",addRequired:!1,editRequired:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",awRequiredWhen:{variable:"teamrequired",init:"true"}}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",add:"Add a new credential"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Modify the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{add:{ngClick:"add('projects')",icon:"icon-plus",label:"Add"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('projects', project.id, project.name)",icon:"icon-edit",awToolTip:"Modify the project","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('projects', project.id, project.name, 'projects')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the project"}}},users:{type:"collection",title:"Users",iterator:"user",open:!1,actions:{add:{ngClick:"add('users')",icon:"icon-plus",label:"Add",awToolTip:"Add a user"}},fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('users', user.id, user.username)",icon:"icon-edit",awToolTip:"Edit user","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('users', user.id, user.username, 'users')",icon:"icon-terash","class":"btn-danger",awToolTip:"Remove user"}}}}}),angular.module("UserFormDefinition",[]).value("UserForm",{addTitle:"Create User",editTitle:"{{ username }}",name:"user",well:!0,forceListeners:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{first_name:{label:"First Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},last_name:{label:"Last Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},email:{label:"Email",type:"email",addRequired:!0,editRequired:!0,autocomplete:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",excludeMode:"edit",awRequiredWhen:{variable:"orgrequired",init:!0}},username:{label:"Username",type:"text",awRequiredWhen:{variable:"not_ldap_user",init:!0},autocomplete:!1},password:{label:"Password",type:"password",ngShow:"ldap_user == false",addRequired:!0,editRequired:!1,ngChange:"clearPWConfirm('password_confirm')",autocomplete:!1,chkPass:!0},password_confirm:{label:"Confirm Password",type:"password",ngShow:"ldap_user == false",addRequired:!1,editRequired:!1,awPassMatch:!0,associated:"password",autocomplete:!1},is_superuser:{label:"Superuser (User has full system administration privileges.)",type:"checkbox",trueValue:"true",falseValue:"false","default":"false",ngShow:"current_user['is_superuser'] == true"},ldap_user:{label:"Created by LDAP",type:"checkbox",readonly:!0}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",awToolTip:"Add a credential for this user"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Edit the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},admin_of_organizations:{type:"collection",title:"Admin of Organizations",iterator:"adminof",open:!1,base:"/organizations",actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},teams:{type:"collection",title:"Teams",iterator:"team",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}}}}),angular.module("InventoryGroupsHelpDefinition",[]).value("InventoryGroupsHelp",{story:{hdr:"Building your inventory",width:510,height:560,steps:[{intro:"Start by creating a group:",img:{src:"groups001.png",maxWidth:338,maxHeight:222},box:'Click on the groups list (the left side of the page) to add a new group.',autoOffNotice:!0},{intro:"Enter group properties:",img:{src:"groups002.png",maxWidth:443,maxHeight:251},box:'Enter the group name, a description and any inventory variables. Variables can be entered using either JSON or YAML syntax. For more on inventory variables, see docs.ansible.com/intro_inventory.html'},{intro:"Cloud inventory: select cloud source",img:{src:"groups003.png",maxWidth:412,maxHeight:215},box:'For a cloud inventory, choose the cloud provider from the list and select your credentials. If you have not already setup credentials for the provider, you will need to do that first on the Credentials tab.'},{intro:"Cloud inventory: synchronize Tower with the cloud",img:{src:"groups004.png",maxWidth:261,maxHeight:221},box:'To pull the cloud inventory into Tower, initiate an inventory sync by clicking .'},{intro:"Groups can have subgroups:",img:{src:"groups005.png",maxWidth:430,maxHeight:206},box:'
First, select a group. Then click to create a new group. The new group will be added to the selected group.
'},{intro:"Copy or move groups:",img:{src:"groups006.png",maxWidth:263,maxHeight:211},box:'
Copy or move a group by dragging and dropping its name onto another group name. A dialog will appear asking if the group should be coppied or moved.
Your Ansible Tower license has reached capacity for the number of managed hosts allowed. You will not be able to add any additional hosts.
"+i,c(d,f,g,null,!0)))}}]),angular.module("ChildrenHelper",["RestServices","Utilities"]).factory("ToggleChildren",[function(){return function(a){function b(a){var b;for(i[a].ngicon="fa fa-minus-square-o node-toggle",b=a+1;b10?10:i,i=3>i?3:i,f.fields[h].rows=i);break;case"results":if(a.event_data&&a.event_data.res&&void 0===a.event_data.res[h])delete f.fields[h];else if(Array.isArray(a.event_data.res[h])&&0!==a.event_data.res[h].length){for(j="",c=0;c10?10:i,i=3>i?3:i,f.fields[h].rows=i)}else delete f.fields[h];break;case"module_name":case"module_args":a.event_data&&a.event_data.res&&(void 0===a.event_data.res.invocation||void 0===a.event_data.res.invocation[h])&&delete f.fields[h]}b=d.inject(f,{mode:"edit",modal:!0,related:!1}),d.reset(),b.formModalAction=function(){$("#form-modal").modal("hide")},b.formModalActionLabel="OK",b.formModalCancelShow=!1,b.formModalInfo="View JSON",$("#form-modal .btn-success").removeClass("btn-success").addClass("btn-none"),$("#form-modal").addClass("skinny-modal"),b.formModalHeader=a.event_display.replace(/^\u00a0*/g,""),b.formModalInfoAction=function(){var b=g,c=b.inject(l,{mode:"edit",modal:!0,related:!1,modal_selector:"#form-modal2",modal_body_id:"form-modal2-body",modal_title_id:"formModal2Header"});b.reset(),c.formModal2Header=a.event_display.replace(/^\u00a0*/g,""),c.event_data=JSON.stringify(a.event_data,null," "),c.formModal2ActionLabel="OK",c.formModal2CancelShow=!1,c.formModal2Info=!1,c.formModalInfo="View JSON",c.formModal2Action=function(){$("#form-modal2").modal("hide")},$("#form-modal2 .btn-success").removeClass("btn-success").addClass("btn-none")},"string"==typeof a.event_data.res&&(b.traceback=a.event_data.res);for(h in f.fields)switch(h){case"status":b.status=a.failed?"error":a.changed?"changed":"success";break;case"created":n=new Date(a.created),b.created=k(n);break;case"host":a.summary_fields&&a.summary_fields.host&&(b.host=a.summary_fields.host.name);break;case"id":case"task":case"play":b[h]=a[h];break;case"start":case"end":a.event_data&&a.event_data.res&&!m(a.event_data.res[h])&&(b[h]=a.event_data.res[h]);break;case"results":if(Array.isArray(a.event_data.res[h])&&a.event_data.res[h].length>0){for(j="",c=0;c button.',"alert-info"):(f("start"),a.setUrl(l.related.inventory_source),a.get().success(function(a){var b=a.related.current_update?a.related.current_update:a.related.last_update;d({group_name:a.summary_fields.group.name,last_update:b,license_error:a.summary_fields.last_update&&a.summary_fields.last_update.license_error?!0:!1,tree_id:j,group_id:k,parent_scope:i})}).error(function(a,c){f("stop"),b(i,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+l.related.inventory_source+" POST returned status: "+c})})))}}]).factory("GetHostsStatusMsg",[function(){return function(a){var b,c,d,e=a.active_failures,f=a.total_hosts;return e>0?(b=f+(1===f?" host":" hosts")+". "+e+" with failed jobs.",d="true",c=!0):(c=!1,0===f?(b="Group contains 0 hosts.",d="na"):(b=f+(1===f?" host":" hosts")+". No job failures",d="false")),{tooltip:b,failures:c,"class":d}}}]).factory("GetSyncStatusMsg",[function(){return function(a){var b,c,d,e=a.status,f="",g="Start sync process";switch(b=e,c="icon-cloud-"+b,e){case"never updated":b="never",c="icon-cloud-na disabled",d='Sync not performed. Click to start it now.';break;case"none":case"":f="btn-disabled",b="n/a",c="icon-cloud-na disabled",d='Cloud source not configured. Click to update.',g=d;break;case"failed":d="Sync failed. Click to view log.";break;case"successful":d="Sync completed. Click to view log.";break;case"updating":d="Sync running"}return{"class":c,tooltip:d,status:b,launch_class:f,launch_tip:g}}}]).factory("SourceChange",["GetBasePath","CredentialList","LookUpInit","Empty",function(a,b,c,d){return function(e){var f,g,h=e.scope,i=e.form;d(h.source)||("file"===h.source.value?h.sourcePathRequired=!0:(h.sourcePathRequired=!1,h.source_path="",h[i.name+"_form"].source_path.$setValidity("required",!0)),"rax"===h.source.value?(h.source_region_choices=h.rax_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])):"ec2"===h.source.value&&(h.source_region_choices=h.ec2_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])),("rax"===h.source.value||"ec2"===h.source.value)&&(f="rax"===h.source.value?"rax":"aws",g=a("credentials")+"?cloud=true&kind="+f,c({url:g,scope:h,form:i,list:b,field:"credential"})))}}]).factory("GroupsCancelUpdate",["Rest","ProcessErrors","Alert","Wait","Find",function(a,b,c,d,e){return function(f){var g,h=f.scope,i=f.tree_id;h.removeCancelUpdate&&h.removeCancelUpdate(),h.removeCancelUpdate=h.$on("CancelUpdate",function(e,f){a.setUrl(f),a.post().success(function(){d("stop"),c("Inventory Sync Cancelled",'Your request to cancel the sync process was submitted to the task manger. Click the button to monitor the status.',"alert-info")}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+f+" failed. POST status: "+c})})}),h.removeCheckCancel&&h.removeCheckCancel(),h.removeCheckCancel=h.$on("CheckCancel",function(e,f,g){var i=g?g:f;i+="cancel/",a.setUrl(i),a.get().success(function(a){a.can_cancel?h.$emit("CancelUpdate",i):(d("stop"),c("Cancel Inventory Sync",'Either you do not have access or the sync process completed. Click the button to view the latest status.',"alert-info"))}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+i+" failed. GET status: "+c})})}),g=e({list:h.groups,key:"id",val:i}),h.selected_tree_id=g.id,h.selected_group_id=g.group_id,!g||"updating"!==g.status&&"pending"!==g.status?c("Cancel Inventory Sync",'The sync process completed. Click the to view the latest status.',"alert-info"):(d("start"),a.setUrl(g.related.inventory_source),a.get().success(function(a){h.$emit("CheckCancel",a.related.last_update,a.related.current_update)}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+g.related.inventory_source+" failed. GET status: "+c})}))}}]).factory("GroupsAdd",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","ParseTypeChange","GroupsEdit","Wait","GetChoices","GetSourceTypeOptions","LookUpInit","BuildTree","SourceChange","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){return function(b){var c,d=b.inventory_id,i=void 0!==b.group_id?b.group_id:null,m=b.scope,q=null!==i?k("groups")+i+"/children/":k("inventory")+d+"/groups/",u=g,v=h,w=v.inject(u,{mode:"add",modal:!0,related:!1,show_modal:!1});$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),w.formModalActionLabel="Save",w.formModalCancelShow=!0,w.parseType="yaml",w.source=null,l(w),v.reset(),w.removeAddTreeRefreshed&&w.removeAddTreeRefreshed(),w.removeAddTreeRefreshed=w.$on("GroupTreeRefreshed",function(){a.formModalHeader=null,a.formModalCancleShow=null,a.formModalActionLabel=null,n("stop"),$("#form-modal").modal("hide"),w.removeAddTreeRefreshed()}),w.removeSaveComplete&&w.removeSaveComplete(),w.removeSaveComplete=w.$on("SaveComplete",function(a,b,c){c||(w.searchCleanup&&w.searchCleanup(),w.formModalActionDisabled=!1,r({scope:m,inventory_id:d,refresh:!0,new_group_id:b}),t())}),w.removeFormSaveSuccess&&w.removeFormSaveSuccess(),w.removeFormSaveSuccess=w.$on("formSaveSuccess",function(a,b,c){var d,g,h,i,k=!1,l={};if(null!==w.source.value&&""!==w.source.value){for(l.group=b,l.source=w.source.value,l.source_path=w.source_path,l.credential=w.credential,l.overwrite=w.overwrite,l.overwrite_vars=w.overwrite_vars,l.update_on_launch=w.update_on_launch,d=$("#s2id_group_source_regions").select2("data"),g=[],h=0;h"+A.summary_fields.group.name+". Use the Refresh button to monitor the status.","alert-info"):o({scope:A,group_id:d,url:A.group_update_url,group_name:A.name,group_source:A.source.value})},A.sourceChange=function(){v({scope:A,form:g})}}}]).factory("GroupsDelete",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","Wait","BuildTree","Find",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){return function(a){var b,c=a.scope,d=a.tree_id,f=a.inventory_id,g=n({list:c.groups,key:"id",val:d}),h=k("inventory")+f+"/groups/";b=function(){$("#prompt-modal").on("hidden.bs.modal",function(){l("start")}),$("#prompt-modal").modal("hide"),e.setUrl(h),e.post({id:g.group_id,disassociate:1}).success(function(){$("#prompt-modal").off(),c.$emit("GroupDeleteCompleted")}).error(function(a,b){l("stop"),j(c,a,b,null,{hdr:"Error!",msg:"Call to "+h+" failed. POST returned status: "+b})})},i({hdr:"Delete Group",body:"
Are you sure you want to delete group "+g.name+"?
",action:b,"class":"btn-danger"})}}]).factory("ShowUpdateStatus",["$rootScope","$location","$log","$routeParams","Rest","Alert","GenerateForm","Prompt","ProcessErrors","GetBasePath","FormatDate","InventoryStatusForm","Wait","Empty","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){return function(a){function b(a){var b,d;return b=a.match(/\n/g),d=b?b.length:1,d>c?c:d}var c,d,h,j,n,p,q,r=a.group_name,s=a.last_update,t=g,u=l,v=a.license_error;void 0===s||null===s||""===s?(m("stop"),f("Missing Configuration","The selected group is not configured for inventory sync. Edit the group and provide Source information.","alert-info")):(d='
\n
\n',$("#inventory-modal-container").empty().append(d),h=t.inject(u,{mode:"edit",id:"form-container",breadCrumbs:!1,related:!1}),j=$(document).width(),n=$("body").height(),j>1199?(p=675,q=750>n?n-20:750,c=18):1199>=j&&j>=768?(p=550,q=620>n?n-15:620,c=12):(p=j-20,q=500>n?n:500,c=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:p,height:q,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#inventory-modal-container").empty(),o()},open:function(){m("stop")}}),e.setUrl(s),e.get().success(function(a){for(var c in u.fields)a[c]&&(h[c]="created"===c?k(new Date(a[c])):a[c]);h.license_error=v,h.status_rows=b(a.status),h.stdout_rows=b(a.result_stdout),h.traceback_rows=b(a.result_traceback),$("#status-modal-dialog").dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(h,a,b,null,{hdr:"Error!",msg:"Failed to retrieve last update: "+s+". GET status: "+b})}))}}]),angular.module("HostsHelper",["RestServices","Utilities","ListGenerator","HostListDefinition","SearchHelper","PaginationHelpers","ListGenerator","AuthService","HostsHelper","InventoryHelper","RelatedSearchHelper","InventoryFormDefinition","SelectionHelper","HostGroupsFormDefinition"]).factory("SetEnabledMsg",[function(){return function(a){a.enabledToolTip=a.has_inventory_sources?a.enabled?"Host is available":"Host is not available":a.enabled?"Host is available. Click to toggle.":"Host is not available. Click to toggle."}}]).factory("SetHostStatus",["SetEnabledMsg",function(a){return function(b){b.activeFailuresLink="/#/hosts/"+b.id+"/job_host_summaries/?inventory="+b.inventory+"&host_name="+encodeURI(b.name),b.has_active_failures===!0?(b.badgeToolTip="Most recent job failed. Click to view jobs.",b.active_failures="failed"):b.has_active_failures===!1&&null===b.last_job?(b.has_active_failures="none",b.badgeToolTip="No job data available.",b.active_failures="n/a"):b.has_active_failures===!1&&null!==b.last_job&&(b.badgeToolTip="Most recent job successful. Click to view jobs.",b.active_failures="success"),b.enabled_flag=b.enabled,a(b)}}]).factory("SetStatus",["SetEnabledMsg","Empty",function(a,b){return function(c){function d(a){return a.length>25?a.substr(0,25)+"...":a}function e(a){var b,c,e;if(a.has_active_failures===!0||a.has_active_failures===!1&&null!==a.last_job)if(a.has_active_failures===!0?(a.badgeToolTip="Most recent job failed. Click to view jobs.",a.active_failures="failed"):(a.badgeToolTip="Most recent job successful. Click to view jobs.",a.active_failures="success"),a.summary_fields.recent_jobs.length>0){for(e=a.summary_fields.recent_jobs.sort(function(a,b){return-1*(a-b)}),h="Recent Jobs",g='
";else a.has_active_failures===!1&&null===a.last_job&&(a.has_active_failures="none",a.badgeToolTip="No job data available.",a.active_failures="n/a");a.job_status_html=g,a.job_status_title=h}var f,g,h,i=c.scope,j=c.host;if(b(j))for(f=0;fAre you sure you want to delete host "+j+" from group "+n.name+"?":"
\n",d=j("hosts")+l+"/",f=o.inject(null,{mode:"edit",modal:!0,related:!1,html:c}),b=0;bGroups',f.formModalCancelShow=!0,f.formModalActionDisabled=!0,$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),f.hostGroupChangeRemove&&f.hostGroupChangeRemove(),f.hostGroupChangeRemove=f.$on("hostGroupChange",function(){p.pop(),0===p.length&&(h=function(){setTimeout(function(){m("stop")},500)},k({scope:f,inventory_id:n,group_id:f.group_id,action:h}))}),f.formModalAction=function(){var a,b,c;for($("#form-modal").modal("hide"),m("start"),a=0;a0?(f.assignedGroups=null,f.leftButtonDisabled=!0,f.rightButtonDisabled=!1):f.rightButtonDisabled=!0},f.rightChange=function(){null!==f.assignedGroups&&f.assignedGroups.length>0?(f.selectedGroups=null,f.leftButtonDisabled=!1,f.rightButtonDisabled=!0):f.leftButtonDisabled=!0},f.moveLeft=function(){var a,b,c,d;for(a=0;af.available_groups[b].name.toLowerCase()&&f.assignedGroups[a].name.toLowerCase()f.host_groups[b].name.toLowerCase()&&f.selectedGroups[a].name.toLowerCase()0){for(j("stop"),u+='\n",m=angular.element(document.getElementById("password-body")),m.html(u),c(m.contents())(q),$("#password-modal").modal(),$("#password-modal").on("shown.bs.modal",function(){$("#password-body").find('input[type="password"]:first').focus()})}else q.startJob()}}]).factory("SubmitJob",["PromptPasswords","$compile","Rest","$location","GetBasePath","CredentialList","LookUpInit","CredentialForm","ProcessErrors","JobTemplateForm","Wait",function(a,b,c,d,e,f,g,h,i,j,k){return function(b){function l(b){var e,f,g;m.credentialWatchRemove&&m.credentialWatchRemove(),e=(new Date).toISOString(),f=b.related.jobs?b.related.jobs:b.related.job_template+"jobs/",g=o?o:b.name,k("start"),c.setUrl(f),c.post({name:g+" "+e,description:b.description,job_template:b.id,inventory:b.inventory,project:b.project,playbook:b.playbook,credential:b.credential,forks:b.forks,limit:b.limit,verbosity:b.verbosity,extra_vars:b.extra_vars}).success(function(b){m.job_id=b.id,b.passwords_needed_to_start.length>0?a({scope:m,passwords:b.passwords_needed_to_start,start_url:b.related.start,form:h}):(c.setUrl(b.related.start),c.post().success(function(){k("stop");var a=d.path().replace(/^\//,"").split("/")[0];"jobs"===a?m.refresh():d.path("/jobs")}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to start job. POST returned status: "+b})}))}).error(function(a,b){k("stop"),i(m,a,b,null,{hdr:"Error!",msg:"Failed to create job. POST returned status: "+b})})}var m=b.scope,n=b.id,o=b.template?b.template:null,p=d.path().replace(/^\//,"").split("/")[0],q=e(p)+n+"/";k("start"),c.setUrl(q),c.get().success(function(a){m.credential="",""===a.credential||null===a.credential?(k("stop"),m.credentialWatchRemove&&m.credentialWatchRemove(),m.credentialWatchRemove=m.$watch("credential",function(b,c){b!==c&&""!==m.credential&&null!==m.credential&&void 0!==m.credential&&(a.credential=m.credential,l(a))}),g({scope:m,form:j,current_item:null,list:f,field:"credential",hdr:"Credential Required"}),m.lookUpCredential()):l(a)}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to get job template details. GET returned status: "+b})})}}]).factory("ProjectUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","ProjectsForm","Wait",function(a,b,c,d,e,f,g,h,i){return function(b){var d=b.scope,j=b.project_id,k=e("projects")+j+"/update/";d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(){i("stop"),g("Update Started","The request to start the SCM update process was submitted. To monitor the update status, refresh the page by clicking the Refresh button.","alert-info"),d.refresh()}),d.removeSCMSubmit&&d.removeSCMSubmit(),d.removeSCMSubmit=d.$on("SCMSubmit",function(b,c,e){a({scope:d,passwords:c,start_url:k,form:h,extra_html:e})}),i("start"),c.setUrl(k),c.get().success(function(a){var b,c;if(i("stop"),a.can_update){for(c="",b=0;b\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="\n",d.projects[b].scm_username&&(c+='
\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="
\n");break}c+="",d.$emit("SCMSubmit",a.passwords_needed_to_update,c)}else g("Permission Denied","You do not have access to update this project. Please contact your system administrator.","alert-danger")}).error(function(a,b){f(d,a,b,null,{hdr:"Error!",msg:"Failed to get project update details: "+k+" GET status: "+b})})}}]).factory("InventoryUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","GroupForm","BuildTree","Wait",function(a,b,c,d,e,f,g,h,i,j){return function(b){var d=b.scope,e=b.url,i=b.group_id,k=b.tree_id;d.removeHostReloadComplete&&d.removeHostReloadComplete(),d.removeHostReloadComplete=d.$on("HostReloadComplete",function(){j("stop"),g("Update Started",'Your request to start the inventory sync process was submitted. Monitor progress by clicking the button.',"alert-info"),d.removeHostReloadComplete&&d.removeHostReloadComplete()}),d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(a,b){"started"===b&&(d.refreshGroups?(d.selected_tree_id=k,d.selected_group_id=i,d.refreshGroups()):d.refresh&&d.refresh(),d.$emit("HostReloadComplete"))}),d.removeInventorySubmit&&d.removeInventorySubmit(),d.removeInventorySubmit=d.$on("InventorySubmit",function(b,c,f){a({scope:d,passwords:c,start_url:e,form:h,extra_html:f})}),j("start"),c.setUrl(e),c.get().success(function(a){a.can_update?d.$emit("InventorySubmit",a.passwords_needed_to_update):(j("stop"),g("Permission Denied","You do not have access to run the update. Please contact your system administrator.","alert-danger"))}).error(function(a,b){j("stop"),f(d,a,b,null,{hdr:"Error!",msg:"Failed to get inventory_source details. "+e+"GET status: "+b})})}}]),angular.module("JobsHelper",["Utilities","FormGenerator","JobSummaryDefinition","InventoryHelper"]).factory("JobStatusToolTip",[function(){return function(a){var b;switch(a){case"successful":case"success":b="There were no failed tasks.";break;case"failed":b="Some tasks encountered errors.";break;case"canceled":b="Stopped by user request.";break;case"new":b="In queue, waiting on task manager.";break;case"waiting":b="SCM Update or Inventory Update is executing.";break;case"pending":b="Not in queue, waiting on task manager.";break;case"running":b="Playbook tasks executing."}return b}}]).factory("ShowJobSummary",["Rest","Wait","GetBasePath","FormatDate","ProcessErrors","GenerateForm","JobSummary","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h){return function(i){function j(a){var b=a.match(/\n/g),c=b?b.length:1;return c>p?20:c}var k,l,m,n,o,p,q,r,s=i.job_id,t=f,u=g;r='
Only allow the user or team to view the inventory.
\n
Write
\n
Allow the user or team to modify hosts and groups contained in the inventory, add new hosts and groups, and perform inventory sync operations.\n
Admin
\n
Allow the user or team full access to the inventory. This includes reading, writing, deletion of the inventory and inventory sync operations.
\n
\n"):(b.projectrequired=!0,b.permissionTypeHelp="
\n
Run
\n
Allow the user or team to perform a live deployment of the project against the inventory. In Run mode modules will be executed, and changes to the inventory will occur.
\n
Check
\n
Only allow the user or team to deploy the project against the inventory as a dry-run operation. In Check mode, module operations will only be simulated. No changes will occur.
\n
\n"),c&&(b.permission_type="Inventory"===b.category?"read":"run")}}]),angular.module("ProjectPathHelper",["RestServices","Utilities"]).factory("GetProjectPath",["Alert","Rest","GetBasePath","ProcessErrors",function(a,b,c,d){return function(a){function e(a){var b,c,d=[],e=[];for(b=0;b\n',$("#projects-modal-container").empty().append(b),c=q.inject(r,{mode:"edit",id:"form-container",related:!1,breadCrumbs:!1}),q.reset(),d=$(document).width(),f=$("body").height(),d>1199?(h=675,j=750>f?f-20:750,n=20):1199>=d&&d>=768?(h=550,j=620>f?f-15:620,n=15):(h=d-20,j=500>f?f:500,n=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:h,height:j,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#projects-modal-container").empty()},open:function(){m("stop")}}),e.setUrl(p),e.get().success(function(a){var b,d=a;for(b in r.fields)d[b]?c[b]="created"===b?k(new Date(d[b])):d[b]:d.summary_fields.project[b]&&(c[b]=d.summary_fields.project[b]);$("#status-modal-dialog").dialog({title:d.summary_fields.project.name+" Status"}).dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(c,a,b,r,{hdr:"Error!",msg:"Failed to retrieve status of project: "+o+". GET status: "+b})})}}]),angular.module("SelectionHelper",["Utilities","RestServices"]).factory("SelectionInit",["Rest","Alert","ProcessErrors","ReturnToCaller","Wait",function(a,b,c,d,e){return function(b){var f,g=b.scope,h=b.list,i=b.url,j=b.returnToCaller;f=void 0!==b.selected?b.selected:[],g.formModalActionDisabled=!0,g.disableSelectBtn=!0,g["toggle_"+h.iterator]=function(a,b){var c,d,e;for(c=0;c0?(g.formModalActionDisabled=!1,g.disableSelectBtn=!1):(g.formModalActionDisabled=!0,g.disableSelectBtn=!0)},g.finishSelection=function(){function b(){f=[],void 0!==j?d(j):($("#form-modal").modal("hide"),g.$emit("modalClosed"))}function k(b){a.post(b).success(function(a,b){m.push({result:"success",data:a,status:b}),g.$emit("callFinished")}).error(function(a,b,c){m.push({result:"error",data:a,status:b,headers:c}),g.$emit("callFinished")})}a.setUrl(i);var l,m=[];if(g.formModalActionDisabled=!0,g.disableSelectBtn=!0,e("start"),g.callFinishedRemove&&g.callFinishedRemove(),g.callFinishedRemove=g.$on("callFinished",function(){var a,d=0;if(m.length===f.length){for(e("stop"),a=0;a0)for(l=0;lh)h++,setTimeout(1e3,e());else if("success"===g.status)return d(a)}var f,g={},h=0;return null===c.apiDefaults||void 0===c.apiDefaults?(f="/api/v1/",b.setUrl(f),b.get().success(function(a){var b,d=a;for(b in d)switch(b){case"organizations":d[b].iterator="organization";break;case"jobs":d[b].iterator="job";break;case"users":d[b].iterator="user";break;case"teams":d[b].iterator="team";break;case"hosts":d[b].iterator="host";break;case"groups":d[b].iterator="group";break;case"projects":d[b].iterator="project";break;case"inventories":d[b].iterator="inventory"}c.apiDefaults=d,g={status:"success"}}).error(function(a,b){g={status:"error",msg:"Call to "+f+" failed. GET returned status: "+b}}),e()):d(a)}}]),angular.module("InventoryHelper",["RestServices","Utilities","OrganizationListDefinition","ListGenerator","AuthService","InventoryHelper","InventoryFormDefinition","ParseHelper","SearchHelper"]).factory("WatchInventoryWindowResize",["ApplyEllipsis",function(a){return function(){var b;$(window).resize(function(){clearTimeout(b),b=setTimeout(function(){$("#groups_table .name-column").each(function(){var a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%";$(this).find(".group-name").css({width:e})}),a("#groups_table .group-name a"),a("#hosts_table .host-name a")},100)})}}]).factory("SaveInventory",["InventoryForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","Wait",function(a,b,c,d,e,f,g,h,i){return function(e){var f,h,j,k=e.scope,l=a,m=g("inventory");i("start");try{if(h="json"===k.inventoryParseType?JSON.parse(k.inventory_variables):jsyaml.load(k.inventory_variables),"object"!=typeof h)throw"failed to return an object!";j={};for(f in l.fields)"inventory_variables"!==f&&(l.fields[f].realName?j[l.fields[f].realName]=k[f]:j[f]=k[f]);b.setUrl(m+k.inventory_id+"/"),b.put(j).success(function(a){k.inventory_variables?(b.setUrl(a.related.variable_data),b.put(h).success(function(){i("stop"),k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory varaibles. PUT returned status: "+b})})):k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory. POST returned status: "+b})})}catch(n){i("stop"),c("Error","Error parsing inventory variables. Parser returned: "+n)}}}]).factory("EditInventoryProperties",["InventoryForm","GenerateForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","SaveInventory","Wait","Store","SearchInit",function(a,b,c,d,e,f,g,h,i,j,k,l,m){return function(n){var o,p=n.scope,q=n.inventory_id,r=b,s=a,t={},u=l("CurrentSearchParams");s.well=!1,o=r.inject(s,{mode:"edit",modal:!0,related:!1,modal_show:!1}),s.well=!0,i(o,"inventory_variables","inventoryParseType"),o.inventoryParseType="yaml",o.formModalActionLabel="Save",o.formModalCancelShow=!0,o.formModalInfo=!1,o.formModalHeader="Inventory Properties",k("start"),c.setUrl(h("inventory")+q+"/"),c.get().success(function(a){var b,c;for(b in s.fields){if("inventory_variables"===b){if($.isEmptyObject(a.variables)||"{}"===a.variables||"null"===a.variables||""===a.variables)o.inventory_variables="---";else try{c=JSON.parse(a.variables),o.inventory_variables=jsyaml.safeDump(c)}catch(e){d("Variable Parse Error","Attempted to parse variables for inventory: "+q+". Parse returned: "+e),console&&(console.log(e),console.log("data:"),console.log(a.variables)),o.inventory_variables="---"}t.inventory_variables=o.variables}else"inventory_name"===b?(o[b]=a.name,t[b]=o[b]):"inventory_description"===b?(o[b]=a.description,t[b]=o[b]):a[b]&&(o[b]=a[b],t[b]=o[b]);s.fields[b].sourceModel&&a.summary_fields&&a.summary_fields[s.fields[b].sourceModel]&&(o[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField],t[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField])}f({scope:o,form:s,current_item:o.organization,list:g,field:"organization"}),k("stop"),$("#form-modal").modal("show")}).error(function(a,b){e(o,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+q+". GET returned: "+b})}),o.removeInventorySaved&&o.removeInventorySaved(),o.removeInventorySaved=o.$on("InventorySaved",function(){$("#form-modal").modal("hide"),o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1}),p.$emit("RefreshInventories")}),o.cancelModal=function(){o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1})},o.formModalAction=function(){p.inventory_id=q,p.inventory_name=o.inventory_name,j({scope:o})}}}]),angular.module("md5Helper",["RestServices","Utilities"]).factory("md5Setup",[function(){return function(a){var b=a.scope,c=a.master,d=a.check_field,e=a.default_val;b[d]=e,c[d]=e,b.genMD5=function(a){var c=new Date;b[a]=$.md5("AnsibleWorks"+c.getTime())},b.toggleCallback=function(a){"false"===b.allow_callbacks&&(b[a]="")},b.selectAll=function(a){$('input[name="'+a+'"]').focus().select()}}}]),angular.module("RefreshRelatedHelper",["RestServices","Utilities","PaginationHelpers"]).factory("RefreshRelated",["ProcessErrors","Rest","Wait","PageRangeSetup",function(a,b,c,d){return function(e){var f=e.scope,g=e.set,h=e.iterator,i=e.url;b.setUrl(i),b.get().success(function(a){d({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[g]=a.results,f[h+"Loading"]=!1,f[h+"HoldInput"]=!1,c("stop"),f.$emit("related"+g)}).error(function(b,c){a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RefreshHelper",["RestServices","Utilities","PaginationHelpers"]).factory("Refresh",["ProcessErrors","Rest","Wait","Empty","PageRangeSetup",function(a,b,c,d,e){return function(d){var f=d.scope,g=d.set,h=d.iterator,i=d.url;f.current_url=i,b.setUrl(i),b.get().success(function(a){var b,d;for(e({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[h+"Loading"]=!1,b=1;3>=b;b++)d=1===b?"":b,f[h+"HoldInput"+d]=!1;f[g]=a.results,window.scrollTo(0,0),c("stop"),f.$emit("PostRefresh")}).error(function(b,c){f[h+"HoldInput"]=!1,a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RelatedSearchHelper",["RestServices","Utilities","RefreshRelatedHelper"]).factory("RelatedSearchInit",["$timeout","Alert","Rest","RefreshRelated","Wait",function(a,b,c,d,e){return function(a){function b(a){var b,c,d,e;for(e in h.related)if("tree"!==h.related[e].type&&(void 0===a||a===h.related[e].iterator)){b=h.related[e].iterator;for(d in h.related[e].fields)if(h.related[e].fields[d].key){f[b+"SearchField"]=d,f[b+"SearchFieldLabel"]=h.related[e].fields[d].label;break}f[b+"SortOrder"]=null,f[b+"SearchType"]="icontains",f[b+"SearchTypeLabel"]="Contains",f[b+"SearchValue"]=null,f[b+"SelectShow"]=!1,f[b+"ShowStartBtn"]=!0,f[b+"HideAllStartBtn"]=!1,c=f[b+"SearchField"],!h.related[e].fields[c].searchType||"boolean"!==h.related[e].fields[c].searchType&&"select"!==h.related[e].fields[c].searchType||(f[b+"SelectShow"]=!0,f[b+"SearchSelectOpts"]=h.fields[c].searchOptions),h.related[e].fields[c].searchType&&"gtzero"===h.related[e].fields[c].searchType&&(f[b+"InputHide"]=!0)}}var c,f=a.scope,g=a.relatedSets,h=a.form;b(),f.resetSearch=function(a){b(a),f.search(a)},f.setSearchField=function(a,b,c){var d,e;for(e in h.related)h.related[e].iterator===a&&(d=h.related[e].fields[b]);f[a+"SearchFieldLabel"]=c,f[a+"SearchField"]=b,f[a+"SearchValue"]="",f[a+"SelectShow"]=!1,f[a+"InputHide"]=!1,f[a+"ShowStartBtn"]=!0,void 0!==d.searchType&&"gtzero"===d.searchType&&(f[a+"InputHide"]=!0,f[a+"ShowStartBtn"]=!1),void 0===d.searchType||"boolean"!==d.searchType&&"select"!==d.searchType||(f[a+"SelectShow"]=!0,f[a+"SearchSelectOpts"]=d.searchOptions),void 0!==d.searchType&&"int"===d.searchType&&(f[a+"SearchType"]="int"),f.search(a)},f.setSearchType=function(a,b,c){f[a+"SearchTypeLabel"]=c,f[a+"SearchType"]=b,f.search(a)},f.startSearch=function(a,b){13===a.keyCode&&f.search(b)},f.search=function(a){e("start"),f[a+"Loading"]=!0,f[a+"HoldInput"]=!0,f[a+"SearchValue"]&&(f[a+"ShowStartBtn"]=!1),"host"===a&&"has_active_failures"===f.hostSearchField&&(f.hostFailureFilter=f.hostSearchSelectValue&&1===f.hostSearchSelectValue.value?!0:!1);var b,i,j,k,l;for(i in g)if(g[i].iterator===a){j=i,k=g[i].url;for(b in h.related[i].fields)h.related[i].fields[b].key&&(l=h.related[i].fields[b].desc?"-"+b:b);break}l=null===f[a+"SortOrder"]?l:f[a+"SortOrder"],c=h.related[j].fields[f[a+"SearchField"]],f[a+"SelectShow"]===!1&&""!==f[a+"SearchValue"]&&void 0!==f[a+"SearchValue"]||f[a+"SelectShow"]&&f[a+"SearchSelectValue"]||c.searchType&&"gtzero"===c.searchType?(f[a+"SearchParams"]=c.sourceModel?c.sourceModel+"__"+c.sourceField+"__":c.searchField?c.searchField+"__":f[a+"SearchField"]+"__",f[a+"SearchParams"]+=!c.searchType||"int"!==c.searchType&&"boolean"!==c.searchType?c.searchType&&"gtzero"===c.searchType?"gt=0":f[a+"SearchType"]+"=":"int=",!c.searchType||"boolean"!==c.searchType&&"select"!==c.searchType?(void 0===c.searchType||"gtzero"===c.searchType)&&(f[a+"SearchParams"]+=encodeURI(f[a+"SearchValue"])):f[a+"SearchParams"]+=f[a+"SearchSelectValue"].value,f[a+"SearchParams"]+=l?"&order_by="+encodeURI(l):""):f[a+"SearchParams"]=l?"order_by="+encodeURI(l):"",f[a+"Page"]=0,k+=k.match(/\/$/)?"?":"&",k+=f[a+"SearchParams"],k+=f[a+"PageSize"]?"&page_size="+f[a+"PageSize"]:"",d({scope:f,set:j,iterator:a,url:k})},f.sort=function(a,b){var c,d,e,g;$("."+a+" .list-header").each(function(){if($(this).attr("id")!==a+"-"+b+"-header"){var c=$(this).find("i");c.attr("class","icon-sort")}}),d=$("#"+a+"-"+b+"-header i"),e="",d.hasClass("icon-sort")?(d.removeClass("icon-sort"),d.addClass("icon-sort-up")):d.hasClass("icon-sort-up")?(d.removeClass("icon-sort-up"),d.addClass("icon-sort-down"),e="-"):d.hasClass("icon-sort-down")&&(d.removeClass("icon-sort-down"),d.addClass("icon-sort-up"));for(g in h.related)h.related[g].iterator===a&&(c=h.related[g].fields[b].sourceModel?e+h.related[g].fields[b].sourceModel+"__"+h.related[g].fields[b].sourceField:e+b);f[a+"SortOrder"]=c,f.search(a)}}}]),angular.module("SearchHelper",["RestServices","Utilities","RefreshHelper"]).factory("SearchInit",["Alert","Rest","Refresh","$location","GetBasePath","Empty","$timeout","Wait","Store",function(a,b,c,d,e,f,g,h,i){return function(a){function b(a){var b,c,d,e;e=void 0===a||1===a?"":a,l[p+"SearchField"+e]="",l[p+"SearchFieldLabel"+e]="";for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&o.fields[c].key){o.fields[c].sourceModel?(d=o.fields[c].sourceModel+"__"+o.fields[c].sourceField,r=o.fields[c].desc?"-"+d:d):r=o.fields[c].desc?"-"+c:c,(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)&&(l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label);break}if(f(l[p+"SearchField"+e]))for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)){l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label;break}l[p+"SearchType"+e]="icontains",l[p+"SearchTypeLabel"+e]="Contains",l[p+"SearchParams"+e]="",l[p+"SearchValue"+e]="",l[p+"SelectShow"+e]=!1,l[p+"HideSearchType"+e]=!1,l[p+"InputDisable"+e]=!1,l[p+"ExtraParms"+e]="",l[p+"ShowStartBtn"+e]=!0,l[p+"HideAllStartBtn"+e]=!1,l[p+"SearchPlaceholder"+e]=o.fields[l[p+"SearchField"+e]]&&o.fields[l[p+"SearchField"+e]].searchPlaceholder?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]:o.fields[l[p+"SearchField"+e]].searchPlaceholder:"Search",l[p+"InputDisable"+e]=o.fields[l[p+"SearchField"+e]]&&"all"===o.fields[l[p+"SearchField"+e]].searchObject?!0:!1,b=l[p+"SearchField"+e],o.fields[b]&&(!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType||(l[p+"SelectShow"+e]=!0,l[p+"SearchSelectOpts"+e]=o.fields[b].searchOptions),o.fields[b].searchType&&"int"===o.fields[b].searchType&&(l[p+"HideSearchType"+e]=!0),o.fields[b].searchType&&"gtzero"===o.fields[b].searchType&&(l[p+"InputHide"+e]=!0))}var e,g,j,k,l=a.scope,m=a.set,n=a.url,o=a.list,p=a.iterator?a.iterator:o.iterator,q=a.setWidgets===!1?!1:!0,r=a.sort_order||"";if(q)for(e=o.searchWidgets?o.searchWidgets:1,g=1;e>=g;g++)j=1===g?"":g,$("#search-widget-container"+j)&&b(g);k={set:m,defaultUrl:n,list:o,iterator:p,sort_order:r},i("CurrentSearchParams",k),l.setSearchField=function(a,b,c,d){var e=void 0===d||1===d?"":d;l[a+"SearchFieldLabel"+e]=c,l[a+"SearchField"+e]=b,l[a+"SearchValue"+e]="",l[a+"SelectShow"+e]=!1,l[a+"HideSearchType"+e]=!1,l[a+"InputHide"+e]=!1,l[a+"SearchType"+e]="icontains",l[a+"InputDisable"+e]="all"===o.fields[b].searchObject?!0:!1,l[a+"ShowStartBtn"+e]=!0,l[a+"SearchPlaceholder"+e]=o.fields[l[a+"SearchField"+e]]&&o.fields[l[a+"SearchField"+e]].searchPlaceholder?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]:o.fields[l[a+"SearchField"+e]].searchPlaceholder:"Search",o.fields[b].searchType&&"gtzero"===o.fields[b].searchType?(l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1,l.search(a)):o.fields[b].searchSingleValue?(l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"SearchSelectValue"+e]="boolean"===o.fields[b].searchType&&"true"===o.fields[b].searchValue?{value:1}:"boolean"===o.fields[b].searchType&&"false"===o.fields[b].searchValue?{value:0}:{value:o.fields[b].searchValue},l[a+"ShowStartBtn"+e]=!1):"in"===o.fields[b].searchType?(l[a+"SearchType"+e]="in",l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1):!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType&&"select_or"!==o.fields[b].searchType?o.fields[b].searchType&&"int"===o.fields[b].searchType?l[a+"SearchType"+e]="int":o.fields[b].searchType&&"isnull"===o.fields[b].searchType&&(l[a+"SearchType"+e]="isnull",l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]="true",l[a+"ShowStartBtn"+e]=!1):(l[a+"SelectShow"+e]=!0,l[a+"SearchSelectOpts"+e]=o.fields[b].searchOptions),l.search(a)},l.resetSearch=function(a){var c,e=o.searchWidgets?o.searchWidgets:1;for(c=1;e>=c;c++)b(c);window.location="/#"+d.path(),l.search(a)},l.removeDoSearch&&l.removeDoSearch(),l.removeDoSearch=l.$on("doSearch",function(a,b,d,e){l[b+"Loading"]=void 0===e||e===!0?!0:!1;var f,g=n;l[b+"Page"]=d?parseInt(d)-1:0,l[b+"SearchParams"]&&(g+=/\/$/.test(g)?"?"+l[b+"SearchParams"]:"&"+l[b+"SearchParams"]),f=/\/$/.test(g)?"?":"&",g+=l[b+"_page_size"]?f+"page_size="+l[b+"_page_size"]:"",d&&(f=/\/$/.test(g)?"?":"&",g+=f+"page="+d),l[b+"ExtraParms"]&&(f=/\/$/.test(g)?"?":"&",g+=f+l[b+"ExtraParms"]),g=g.replace(/\&\&/,"&"),c({scope:l,set:m,iterator:b,url:g})}),l.removePrepareSearch&&l.removePrepareSearch(),l.removePrepareSearch=l.$on("prepareSearch",function(a,b,c,d,e){h("start"),l[b+"SearchParams"]="";var f,g,i=o.searchWidgets?o.searchWidgets:1;for(f=1;i>=f;f++)g=1===f?"":f,$("#search-widget-container"+g)&&o.fields[l[b+"SearchField"+g]]&&o.fields[l[b+"SearchField"+g]].searchObject&&("all"!==o.fields[l[b+"SearchField"+g]].searchObject?(l[b+"HideAllStartBtn"+g]=!1,l[b+"SearchValue"+g]?(l[b+"ShowStartBtn"+g]=!1,l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+g]].searchOnID?"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__id="+l[b+"SearchValue"+g]:"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__name__icontains="+l[b+"SearchValue"+g]):(l[b+"ShowStartBtn"+g]=!0,l[b+"SearchParams"]+="&"+o.fields[l[b+"SearchField"+g]].searchField+"="+o.fields[l[b+"SearchField"+g]].searchObject)):l[b+"HideAllStartBtn"+g]=!0);l.$emit("prepareSearch2",b,c,d,e)}),l.removePrepareSearch2&&l.removePrepareSearch2(),l.removePrepareSearch2=l.$on("prepareSearch2",function(a,b,c,d,e){var g,h,i=o.searchWidgets?o.searchWidgets:1;for(g=1;i>=g;g++)h=1===g?"":g,l[b+"HoldInput"+h]=!0,$("#search-widget-container"+h)&&o.fields[l[b+"SearchField"+h]]&&!o.fields[l[b+"SearchField"+h]].searchObject&&(l[b+"ShowStartBtn"+h]=l[b+"SearchValue"+h]?!1:!0,(!l[b+"SelectShow"+h]&&!f(l[b+"SearchValue"+h])||l[b+"SelectShow"+h]&&l[b+"SearchSelectValue"+h]||o.fields[l[b+"SearchField"+h]]&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+h]].searchField?"&"+o.fields[l[b+"SearchField"+h]].searchField+"__":o.fields[l[b+"SearchField"+h]].sourceModel?"&"+o.fields[l[b+"SearchField"+h]].sourceModel+"__"+o.fields[l[b+"SearchField"+h]].sourceField+"__":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?"&"+l[b+"SearchField"+h]+"__":"&"+l[b+"SearchField"+h]+"__",l[b+"SearchParams"]+=!o.fields[l[b+"SearchField"+h]].searchType||"int"!==o.fields[l[b+"SearchField"+h]].searchType&&"boolean"!==o.fields[l[b+"SearchField"+h]].searchType?o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType?"gt=0":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?l[b+"SearchType"+h]+"=":"iexact=":"int=",!o.fields[l[b+"SearchField"+h]].searchType||"boolean"!==o.fields[l[b+"SearchField"+h]].searchType&&"select"!==o.fields[l[b+"SearchField"+h]].searchType?(!o.fields[l[b+"SearchField"+h]].searchType||o.fields[l[b+"SearchField"+h]].searchType&&"or"!==o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"!==o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=encodeURI(l[b+"SearchValue"+h])):l[b+"SearchParams"]+=l[b+"SearchSelectValue"+h].value));("inventory"===b&&l.inventoryFailureFilter||"host"===b&&l.hostFailureFilter)&&(l[b+"SearchParams"]+="&has_active_failures=true"),r&&(l[b+"SearchParams"]+=l[b+"SearchParams"]?"&":"",l[b+"SearchParams"]+="order_by="+encodeURI(r)),l.$emit("doSearch",b,c,d,e)}),l.startSearch=function(a,b){13===a.keyCode&&l.search(b)},l.search=function(a,b,c){c=void 0===c?!0:!1,c&&(l[m]=[]),l.$emit("prepareSearch",a,b,c)},l.sort=function(a){$(".list-header").each(function(){if($(this).attr("id")!==a+"-header"){var b=$(this).find("i");b.attr("class","fa fa-sort")}});var b=$("#"+a+"-header i"),c="";b.hasClass("fa-sort")?(b.removeClass("fa-sort"),b.addClass("fa-sort-up")):b.hasClass("fa-sort-up")?(b.removeClass("fa-sort-up"),b.addClass("fa-sort-down"),c="-"):b.hasClass("fa-sort-down")&&(b.removeClass("fa-sort-down"),b.addClass("fa-sort-up")),r=o.fields[a].searchField?c+o.fields[a].searchField:o.fields[a].sortField?c+o.fields[a].sortField:o.fields[a].sourceModel?c+o.fields[a].sourceModel+"__"+o.fields[a].sourceField:c+a,l.search(o.iterator)},l.searchCleanup=function(){l.removeDoSearch(),l.removePrepareSearch(),l.removePrepareSearch2()}}}]),angular.module("TeamHelper",["RestServices","Utilities","OrganizationListDefinition","SearchHelper","PaginationHelpers","ListGenerator"]).factory("SetTeamListeners",["Alert","Rest",function(a,b){return function(a){var c=a.scope,d=a.set,e=a.iterator;c.$on("TeamResultFound",function(a,b,f){var g,h,i,j;if(f.length===b.length){for(i="organization",j="organization_name",g=0;gSelect existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.",base:"users",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{},fieldActions:{}}),angular.module("CloudCredentialsListDefinition",[]).value("CloudCredentialList",{name:"cloudcredentials",iterator:"cloudcredential",selectTitle:"Add Cloud Credentials",editTitle:"Cloud Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},team:{label:"Team",ngBind:"credential.team_name",sourceModel:"team",sourceField:"name",excludeModal:!0},user:{label:"User",ngBind:"credential.user_username",sourceModel:"user",sourceField:"username",excludeModal:!0}},actions:{add:{mode:"all",ngClick:"addCredential()","class":"btn-sm",awToolTip:"Create a new credential"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash-o",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("CredentialsListDefinition",[]).value("CredentialList",{name:"credentials",iterator:"credential",selectTitle:"Add Credentials",editTitle:"Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},kind:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0}},actions:{add:{mode:"all",ngClick:"addCredential()",awToolTip:"Create a new credential"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("GroupListDefinition",[]).value("GroupList",{name:"groups",iterator:"group",selectTitle:"Copy Groups",editTitle:"Groups",index:!0,well:!1,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{help:{awPopOver:"Choose groups by clicking on each group you wish to add. Click the Select button to add the groups to the selected inventory group.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Adding Groups"}},fieldActions:{edit:{label:"Edit",ngClick:"editGroup(group.id)",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit group",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteGroup(group.id, group.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete group",dataPlacement:"top"}}}),angular.module("HomeGroupListDefinition",[]).value("HomeGroupList",{name:"home_groups",iterator:"group",editTitle:"Groups",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Group",ngClick:"editGroup(group.id, group.inventory)",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-6 ellipsis"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ /#/inventories/' + group.inventory + '/' }}"},source:{label:"Source",searchType:"select",searchOptions:[{name:"ec2",value:"ec2"},{name:"none",value:""},{name:"rax",value:"rax"}],sourceModel:"inventory_source",sourceField:"source",searchOnly:!0},has_external_source:{label:"Has external source?",searchType:"in",searchValue:"ec2,rax",searchOnly:!0,sourceModel:"inventory_source",sourceField:"source"},has_active_failures:{label:"Has failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},last_update_failed:{label:"Update failed?",searchType:"select",searchSingleValue:!0,searchValue:"failed",searchOnly:!0,sourceModel:"inventory_source",sourceField:"status"},id:{label:"ID",searchOnly:!0}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",awToolTip:"{{ group.status_tooltip }}",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",dataPlacement:"top",ngHref:"/#/inventories/{{ group.inventory }}/",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",ngShow:"(group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate(group.id)",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"(group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{label:"Edit",mode:"all",ngClick:"editGroup(group.id)",awToolTip:"Edit group",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HomeHostListDefinition",[]).value("HomeHostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Name",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-7 ellipsis",ngClick:"editHost(host.id, host.name)"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ '/#/inventories/' + host.inventory }}"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Has failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_inventory_sources:{label:"Has external source?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},id:{label:"ID",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{label:"Edit",ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"}},actions:{stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HostListDefinition",[]).value("HostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,well:!1,fields:{name:{key:!0,label:"Host Name",linkTo:"/inventories/{{ inventory_id }}/hosts/{{ host.id }}"},description:{label:"Description"}},actions:{help:{awPopOver:"Select hosts by clicking on each host you wish to add. Add the selected hosts to the group by clicking the Select button.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Selecting Hosts"}},fieldActions:{edit:{label:"Edit",ngClick:"editHost({{ host.id }})",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit host",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete host",dataPlacement:"top"}}}),angular.module("InventoriesListDefinition",[]).value("InventoryList",{name:"inventories",iterator:"inventory",selectTitle:"Add Inventories",editTitle:"Inventories",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},organization:{label:"Organization",ngBind:"inventory.summary_fields.organization.name",linkTo:"/#/organizations/{{ inventory.organization }}",sourceModel:"organization",sourceField:"name",excludeModal:!0},has_inventory_sources:{label:"Cloud sourced?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_active_failures:{label:"Failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},inventory_sources_with_failures:{label:"Sync failures?",searchType:"gtzero",searchValue:"true",searchOnly:!0}},actions:{add:{mode:"all",ngClick:"addInventory()",awToolTip:"Create a new inventory"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{status:{ngHref:"inventory.status_link",iconClass:"{{ 'fa fa-cloud icon-cloud-' + inventory.status_class }}",awToolTip:"{{ inventory.status_tip }}",dataPlacement:"top"},failed_hosts:{ngHref:"inventory.failed_hosts_link",iconClass:"{{ 'fa icon-failures-' + inventory.failed_hosts_class }}",awToolTip:"{{ inventory.failed_hosts_tip }}",dataPlacement:"top"},edit:{label:"Edit",ngClick:"editInventoryProperties(inventory.id)",awToolTip:"Edit inventory",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteInventory(inventory.id, inventory.names')",awToolTip:"Delete inventory",dataPlacement:"top"}}}),angular.module("InventoryGroupsDefinition",[]).value("InventoryGroups",{name:"groups",iterator:"group",editTitle:"{{ inventory_name }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,filterBy:"{ show: true }","class":"table-condensed table-no-border",fields:{name:{label:"Groups",key:!0,ngClick:"showHosts(group.id,group.group_id, false)",ngClass:"group.selected_class",hasChildren:!0,columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",nosort:!0,awDroppable:"{{ group.isDroppable }}",awDraggable:"{{ group.isDraggable }}",dataContainment:"#groups_table",dataTreeId:"{{ group.id }}",dataGroupId:"{{ group.group_id }}",dataType:"group"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createGroup()",awToolTip:"Create a new group"},properties:{mode:"all",awToolTip:"Edit inventory properties",ngClick:"editInventoryProperties()"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refreshGroups()"},stream:{ngClick:"showGroupActivity()",awToolTip:"View Activity Stream",mode:"all"},help:{mode:"all",awToolTip:"Get help building your inventory",ngClick:"showGroupHelp()",id:"inventory-summary-help"}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",ngShow:"group.id > 1",awToolTip:"{{ group.status_tooltip }}",dataTipWatch:"group.launch_tooltip",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",ngShow:"group.id > 1",dataPlacement:"top",ngClick:"showHosts(group.id, group.group_id, group.show_failures)",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",dataTipWatch:"group.launch_tooltip",ngShow:"group.id > 1 && (group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate({{ group.id }})",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"group.id > 1 && (group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{mode:"all",ngClick:"editGroup({{ group.group_id + ',' + group.id }})",awToolTip:"Edit group",ngShow:"group.id > 1",dataPlacement:"top"},"delete":{mode:"all",ngClick:"deleteGroup({{ group.id + ',' + group.group_id }})",awToolTip:"Delete group",ngShow:"group.id != 1",dataPlacement:"top"}}}),angular.module("InventoryHostsDefinition",[]).value("InventoryHosts",{name:"hosts",iterator:"host",editTitle:"{{ selected_group }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,"class":"table-condensed table-no-border",fields:{name:{key:!0,label:"Hosts",ngClick:"editHost(host.id)",searchPlaceholder:"search_place_holder",columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",dataHostId:"{{ host.id }}",dataType:"host",awDraggable:"true"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"},"delete":{ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash",awToolTip:"Delete host",dataPlacement:"top"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createHost()",ngHide:"selected_tree_id == 1",awToolTip:"Create a new host"},stream:{ngClick:"showHostActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("JobEventsListDefinition",[]).value("JobEventList",{name:"jobevents",iterator:"jobevent",editTitle:"Job Events",index:!1,hover:!0,hasChildren:!0,filterBy:"{ show: true }",navigationLinks:{details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",active:!0,icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",icon:"icon-laptop"}},fields:{created:{label:"Created On",columnClass:"col-lg-1 col-md-1 hidden-sm hidden-xs",key:!0,nosort:!0,searchable:!1,link:!1},status:{label:"Status",showValue:!1,columnClass:"col-sm-1 col-xs-2 text-center",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}],nosort:!0,searchable:!1,ngClick:"viewJobEvent({{ jobevent.id }})",awToolTip:"{{ jobevent.statusBadgeToolTip }}",dataPlacement:"top",badgeIcon:"fa icon-job-{{ jobevent.status }}",badgePlacement:"left",badgeToolTip:"{{ jobevent.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgClick:"viewJobEvent({{ jobevent.id }})"},event_display:{label:"Event",hasChildren:!0,ngClick:"toggleChildren(jobevent.id, jobevent.related.children)",nosort:!0,searchable:!1,ngClass:"{{ jobevent.class }}",appendHTML:"jobevent.event_detail"},host:{label:"Host",ngBind:"jobevent.summary_fields.host.name",ngHref:"{{ jobevent.hostLink }}",searchField:"hosts__name",nosort:!0,searchOnly:!1,id:"job-event-host-header","class":"break",columnClass:"col-lg-2 hidden-sm hidden-xs"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{columnClass:"col-sm-1 col-xs-2",view:{label:"View",ngClick:"viewJobEvent(jobevent.id)",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("JobHostDefinition",[]).value("JobHostList",{name:"jobhosts",iterator:"jobhost",editTitle:"All summaries",index:!0,hover:!0,navigationLinks:{ngHide:"host_id !== null",details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",active:!0,icon:"icon-laptop"}},fields:{job:{label:"Job ID",ngClick:"showJob(jobhost.job)",columnShow:"host_id !== null",key:!0,desc:!0},host:{label:"Host",key:!0,sourceModel:"host",sourceField:"name",ngBind:"jobhost.host_name",ngHref:"jobhost.hostLinkTo"},status:{label:"Status",badgeNgHref:"{{ jobhost.statusLinkTo }}",badgeIcon:"fa icon-job-{{ jobhost.status }}",badgePlacement:"left",badgeToolTip:"{{ jobhost.statusBadgeToolTip }}",badgeTipPlacement:"top",ngHref:"{{ jobhost.statusLinkTo }}",awToolTip:"{{ jobhost.statusBadgeToolTip }}",dataPlacement:"top",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}]},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},ok:{label:"Success",searchable:!1},changed:{label:"Changed",searchable:!1},failures:{label:"Failure",searchable:!0,searchLabel:"Contains failed events?",searchType:"gtzero"},dark:{label:"Unreachable",searchable:!0,searchType:"gtzero",searchLabel:"Contains unreachable hosts?"},skipped:{label:"Skipped",searchable:!1}},actions:{help:{awPopOver:"
\n
Success
Tasks successfully executed on the host.
\n
Changed
Actions taken on the host.
\n
Failure
Tasks that failed on the host.
\n
Unreachable
Times the ansible server could not reach the host.
\n
Skipped
Tasks bypassed and not performed on the host due to prior task failure or the host being unreachable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Job Host Summary",id:"jobhost-help-button"},refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refresh()",ngShow:"host_id == null"}},fieldActions:{}}),angular.module("JobTemplatesListDefinition",[]).value("JobTemplateList",{name:"job_templates",iterator:"job_template",selectTitle:"Add Job Template",editTitle:"Job Templates",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addJobTemplate()",basePaths:["job_templates"],awToolTip:"Create a new template"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editJobTemplate(job_template.id)",icon:"icon-edit",awToolTip:"Edit template","class":"btn-default btn-xs",dataPlacement:"top"},submit:{label:"Launch",icon:"icon-rocket",mode:"all","class":"btn-xs btn-success",ngClick:"submitJob(job_template.id)",awToolTip:"Start a job using this template",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteJobTemplate(job_template.id, job_template.name)",icon:"icon-trash","class":"btn-danger btn-xs",awToolTip:"Delete template",dataPlacement:"top"}}}),angular.module("JobsListDefinition",[]).value("JobList",{name:"jobs",iterator:"job",editTitle:"Jobs",index:!1,hover:!0,"class":"jobs-table",fields:{id:{label:"Job ID",key:!0,desc:!0,searchType:"int"},inventory:{label:"Inventory ID",searchType:"int",searchOnly:!0},created:{label:"Create On",link:!1,searchable:!1},job_template:{label:"Job Template",ngBind:"job.summary_fields.job_template.name",ngHref:"{{ '/#/job_templates/' + job.job_template }}",sourceModel:"job_template",sourceField:"name"},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},status:{label:"Status","class":"job-{{ job.status }}",searchType:"select",linkTo:"{{ job.statusLinkTo }}",searchOptions:[{name:"new",value:"new"},{name:"waiting",value:"waiting"},{name:"pending",value:"pending"},{name:"running",value:"running"},{name:"successful",value:"successful"},{name:"error",value:"error"},{name:"failed",value:"failed"},{name:"canceled",value:"canceled"}],badgeIcon:"fa icon-job-{{ job.status }}",badgePlacement:"left",badgeToolTip:"{{ job.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgHref:"{{ job.statusLinkTo }}",awToolTip:"{{ job.statusBadgeToolTip }}",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{submit:{label:"Relaunch",icon:"icon-rocket",mode:"all",ngClick:"submitJob(job.id, job.summary_fields.job_template.name)",awToolTip:"Start the job",dataPlacement:"top"},cancel:{label:"Stop",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Cancel a running or pending job",ngShow:"job.status == 'pending' || job.status == 'running' || job.status == 'waiting'",dataPlacement:"top"},"delete":{label:"Delete",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Delete the job",ngShow:"job.status != 'pending' && job.status != 'running' && job.status != 'waiting'",dataPlacement:"top"},dropdown:{type:"DropDown",label:"View",icon:"fa-search-plus","class":"btn-default btn-xs",options:[{ngClick:"editJob(job.id, job.summary_fields.job_template.name)",label:"Status"},{ngClick:"viewEvents(job.id, job.summary_fields.job_template.name)",label:"Events",ngHide:"job.status == 'new'"},{ngClick:"viewSummary(job.id, job.summary_fields.job_template.name)",label:"Host Summary",ngHide:"job.status == 'new'"}]}}}),angular.module("OrganizationListDefinition",[]).value("OrganizationList",{name:"organizations",iterator:"organization",selectTitle:"Add Organizations",editTitle:"Organizations",hover:!0,index:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addOrganization()",awToolTip:"Create a new organization"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editOrganization(organization.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit organization",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteOrganization(organization.id, organization.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete organization",dataPlacement:"top"}}}),angular.module("PermissionListDefinition",[]).value("PermissionList",{name:"permissions",iterator:"permission",selectTitle:"Add Permission",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',editTitle:"Permissions",index:!0,well:!0,fields:{name:{key:!0,label:"Name",ngClick:"editPermission(permission.id)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},actions:{add:{mode:"all",ngClick:"addPermission()",awToolTip:"Add a new permission",ngShow:"PermissionAddAllowed"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editPermission(permission.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit permission",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deletePermission(permission.id, permission.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete permission",ngShow:"PermissionAddAllowed",dataPlacement:"top"}}}),angular.module("ProjectsListDefinition",[]).value("ProjectList",{name:"projects",iterator:"project",selectTitle:"Add Project",editTitle:"Projects",selectInstructions:"
Select existing projects by clicking each project or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new project by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",columnClass:"hidden-sm hidden-xs",excludeModal:!0},scm_type:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0},status:{label:"Status",ngClick:"showSCMStatus(project.id)",awToolTip:"View details of last SCM Update",dataPlacement:"top",badgeIcon:"{{ 'fa icon-failures-' + project.badge }}",badgePlacement:"left",searchType:"select",searchOptions:[],excludeModal:!0},last_updated:{label:"Last Updated",type:"date",excludeModal:!0,searchable:!1}},actions:{add:{mode:"all",ngClick:"addProject()",awToolTip:"Create a new project"},help:{awPopOver:"
\n
Updating
A source control update is in progress.
\n
Never Updated
This project has not yet been updated from source control.
\n
Failed
An error occurred during the most recent source control update, click the status text for more information.
\n
Successful
TThe latest source control update completed successfully.
\n
Missing
The previously configured local project directory is missing.
\n
N/A
The project is not linked to source control, so updates are not applicable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all",awToolTip:"Click for help",awTipPlacement:"top"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editProject(project.id)",awToolTip:"Edit project properties",dataPlacement:"top"},scm_update:{label:"Update",ngClick:"SCMUpdate(project.id)",awToolTip:"{{ project.scm_update_tooltip }}",ngClass:"project.scm_type_class",dataPlacement:"top"},cancel:{label:"Stop",ngClick:"cancelUpdate(project.id, project.name)",awToolTip:"Cancel a running SCM update process",ngShow:"project.status == 'updating'",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteProject(project.id, project.name)",awToolTip:"Permanently remove project from the database",ngShow:"project.status !== 'updating'",dataPlacement:"top"}}}),angular.module("StreamListDefinition",[]).value("StreamList",{name:"activities",iterator:"activity",editTitle:"Activity Stream",selectInstructions:"",index:!1,hover:!0,"class":"table-condensed",searchWidgets:3,fields:{timestamp:{label:"Event Time",key:!0,desc:!0,noLink:!0,searchable:!1},user:{label:"Initiated by",ngBindHtml:"activity.user",sourceModel:"actor",sourceField:"username",searchPlaceholder:"Username",searchWidget:1},description:{label:"Action",ngBindHtml:"activity.description",nosort:!0,searchable:!1,columnClass:"col-lg-7"},system_event:{label:"System event",searchOnly:!0,searchType:"isnull",sourceModel:"actor",sourceField:"username",searchWidget:1},all_objects:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All resources",searchWidget:2},credential_search:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Credential name",searchWidget:2,searchField:"object1"},group_search:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Group name",searchWidget:2,searchField:"object1"},host_search:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Host name",searchWidget:2,searchField:"object1"},inventory_search:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Inventory name",searchWidget:2,searchField:"object1"},job_template_search:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Job template name",searchWidget:2,searchField:"object1"},job_search:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:2,searchField:"object1"},organization_search:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Organization name",searchWidget:2,searchField:"object1"},project_search:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Project name",searchWidget:2,searchField:"object1"},user_search:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Primary username",searchWidget:2,searchField:"object1"},all_objects3:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All related resources",searchWidget:3,searchField:"object2"},credential_search3:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Related credential name",searchWidget:3,searchField:"object2"},group_search3:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Related group name",searchWidget:3,searchField:"object2"},host_search3:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Related host name",searchWidget:3,searchField:"object2"},inventory_search3:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Related inventory name",searchWidget:3,searchField:"object2"},job_search3:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:3,searchField:"object2"},job_template_search3:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Related job template name",searchWidget:3,searchField:"object2"},organization_search3:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Related organization name",searchWidget:3,searchField:"object2"},project_search3:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Related project name",searchWidget:3,searchField:"object2"},user_search3:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Related username",searchWidget:3,searchField:"object2"}},actions:{refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refreshStream()"},close:{mode:"all",awToolTip:"Close Activity Stream view",ngClick:"closeStream()"}},fieldActions:{view:{label:"View",ngClick:"showDetail(activity.id)",icon:"fa-zoom-in","class":"btn-default btn-xs",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("TeamsListDefinition",[]).value("TeamList",{name:"teams",iterator:"team",selectTitle:"Add Team",editTitle:"Teams",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"},organization:{label:"Organization",ngBind:"team.organization_name",sourceModel:"organization",sourceField:"name"}},actions:{add:{mode:"all",ngClick:"addTeam()",awToolTip:"Create a new team"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editTeam(team.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit team",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteTeam(team.id, team.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete team",dataPlacement:"top"}}}),angular.module("UserListDefinition",[]).value("UserList",{name:"users",iterator:"user",selectTitle:"Add Users",editTitle:"Users",selectInstructions:"
Select existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.
When available, a brand new user can be created by clicking the green Create New button.
",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{add:{label:"Create New",mode:"all",ngClick:"addUser()",basePaths:["organizations","users"],"class":"btn-xs",awToolTip:"Create a new user"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editUser(user.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit user",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteUser(user.id, user.username)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete user",dataPlacement:"top"}}}),angular.module("InventorySyncStatusWidget",["RestServices","Utilities"]).factory("InventorySyncStatus",["$rootScope","$compile",function(a,b){return function(a){function c(a){var b=a.label,c=a.count,d=a.fail,e=a.link,f=a.fail_link,g="
\n",d+="\n",d+="\n",d+=c({label:"Inventories",count:k.inventories&&k.inventories.total_with_inventory_source?k.inventories.total_with_inventory_source:0,fail:k.inventories&&k.inventories.inventory_failed?k.inventories.inventory_failed:0,link:"/#/inventories/?has_inventory_sources=true",fail_link:"/#/inventories/?inventory_sources_with_failures=true"}),e=0,f=0,k.inventory_sources)for(h in k.inventory_sources)e+=k.inventory_sources[h].total?k.inventory_sources[h].total:0,f+=k.inventory_sources[h].failed?k.inventory_sources[h].failed:0;d+=c({label:"Groups",count:e,fail:f,link:"/#/home/groups/?has_external_source=true",fail_link:"/#/home/groups/?status=failed"});for(h in k.inventory_sources)k.inventory_sources[h].total&&(d+=c({label:k.inventory_sources[h].label,count:k.inventory_sources[h].total?k.inventory_sources[h].total:0,fail:k.inventory_sources[h].failed?k.inventory_sources[h].failed:0,link:"/#/home/groups/?source="+h,fail_link:"/#/home/groups/?status=failed&source="+h}));d+="\n",d+="
\n",e+="\n",e+="\n",f=0,l.scm_types)for(h in l.scm_types)f+=l.scm_types[h].total?l.scm_types[h].total:0;e+=c({label:"Projects",link:"/#/projects",count:f,fail:l.projects&&l.projects.failed?l.projects.failed:0,fail_link:"/#/projects/?status=failed"}),i=[];for(h in l.scm_types)i.push(h);for(i.sort(),d=0;d\n",e+="
\n",e+="
\n",e+="
\n",e+="\n",g=angular.element(document.getElementById(k)),g.html(e),b(g)(j),j.$emit("WidgetLoaded")}}]),angular.module("StreamWidget",["RestServices","Utilities","StreamListDefinition","SearchHelper","PaginationHelpers","RefreshHelper","ListGenerator","StreamWidget","AuthService"]).factory("setStreamHeight",[function(){return function(){var a=$("#stream-content").height(),b=parseInt($("#tab-content-container").css("min-height").replace(/px/,"")),c=a>b?a:b;$("#tab-content-container").css({"min-height":c})}}]).factory("ShowStream",["setStreamHeight","Authorization",function(a){return function(){var b=$("#stream-container");b.css({position:"absolute",top:0,left:0,width:"100%","min-height":"100%","background-color":"#FFF"}),a(),b.show("slide",{direction:"left"},{duration:500,queue:!1})}}]).factory("HideStream",["LoadBreadCrumbs",function(a){return function(){var b=$("#stream-container");b.hide("slide",{direction:"left"},{duration:500,queue:!1}),setTimeout(function(){b.detach(),b.empty(),b.unbind(),$("#tab-content-container").css({"min-height":0})},500),a()}}]).factory("StreamBreadCrumbs",["$rootScope","$location",function(a,b){return function(){a.breadcrumbs=[];var c,d,e,f,g=b.path().split("/");for(g.splice(0,1),e=0;e=f;f++)c+="/"+g[f];for(f=0;f0)for(f=0;e>=f;f++)c+="/"+g[f];else c="/"+g[e];d=g[e],d=d.charAt(0).toUpperCase()+d.slice(1)}a.breadcrumbs.push({path:c,title:d,ngClick:"closeStream('"+c+"')"})}}}]).factory("FixUrl",[function(){return function(a){return a.replace(/\/api\/v1\//,"/#/")}}]).factory("BuildUrl",[function(){return function(a){var b="/#/";switch(a.base){case"group":case"host":b+="home/"+a.base+"s/?id="+a.id;break;case"inventory":b+="inventories/"+a.id+"/";break;default:b+=a.base+"s/"+a.id+"/"}return b}}]).factory("BuildDescription",["FixUrl","BuildUrl",function(a,b){return function(a){function c(a){return a.replace(/^_deleted_\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d+\+\d+:\d+_/,"")}var d,e,f,g,h,i,j,k;d=a.operation,d+=/e$/.test(a.operation)?"d ":"ed ",e=d,f=a.object1,g=a.object2,h=a.summary_fields[f]?a.summary_fields[f][0]:null,i=f===g?a.summary_fields[f][1]:a.summary_fields[g]?a.summary_fields[g][0]:null,("user"===f||"user"===g)&&(a.summary_fields.user[0].name=a.summary_fields.user[0].username),i&&i.name&&!/^_delete/.test(i.name)?(i.base=g,d+=g+' '+i.name+""+("disassociate"===a.operation?" from ":" to "),e+=g+" "+i.name+("disassociate"===a.operation?" from ":" to ")):g&&(j="",i&&i.name&&(j=" "+c(i.name)),d+=g+j+("disassociate"===a.operation?" from ":" to "),e+=g+j+("disassociate"===a.operation?" from ":" to ")),h&&h.name&&!/^\_delete/.test(h.name)?(h.base=f,d+=f+' '+h.name+"",e+=f+" "+h.name):f&&(j="",k="",!h||!h.name||h&&h.name&&/^_delete/.test(h.name)?a.changes&&a.changes.name?"string"==typeof a.changes.name?(j=" "+a.changes.name,k=j):"object"==typeof a.changes.name&&Array.isArray(a.changes.name)&&(j=" "+a.changes.name[0],k=j):"job"===f&&h&&a.changes&&a.changes.job_template?"delete"!==a.operation?(h.base=f,j=' '+h.id+" "+a.changes.job_template+"",k=" "+h.id+" "+a.changes.job_template):(j=" "+h.id+" "+a.changes.job_template,k=j):"job"===f&&h&&("delete"!==a.operation?(h.base=f,j=' '+h.id+"",k=" "+h.id):(j=" "+h.id,k=j)):h&&h.name&&(j=" "+c(h.name),k=j),d+=f+j,e+=f+k),a.description=d,a.description_nolink=e}}]).factory("ShowDetail",["$rootScope","Rest","Alert","GenerateForm","ProcessErrors","GetBasePath","FormatDate","ActivityDetailForm","Empty","Find",function(a,b,c,d,e,f,g,h,i,j){return function(a){var b,c,e,f=a.activity_id,i=a.scope,k=d,l=h,m=j({list:i.activities,key:"id",val:f});m&&(m.changes_stringified=JSON.stringify(m.changes,null," "),b=m.changes_stringified.match(/\n/g),c=b?b.length:1,c=1>c?3:10,l.fields.changes.rows=10,e=k.inject(l,{mode:"edit",modal:!0,related:!1}),e.changes=m.changes_stringified,e.user=(m.summary_fields.actor?m.summary_fields.actor.username:"system")+" on "+g(new Date(m.timestamps)),e.operation=m.description_nolink,e.formModalAction=function(){$("#form-modal").modal("hide")},$("#form-modal").on("show.bs.modal",function(){$("#form-modal-body").css({width:"auto",height:"auto","max-height":"100%"})}),e.formModalActionLabel="OK",e.formModalCancelShow=!1,e.formModalInfo=!1,e.formModalHeader="Event "+m.id,e.$$phase||e.$digest())}}]).factory("Stream",["$rootScope","$location","Rest","GetBasePath","ProcessErrors","Wait","StreamList","SearchInit","PaginateInit","GenerateList","FormatDate","ShowStream","HideStream","BuildDescription","FixUrl","BuildUrl","ShowDetail","StreamBreadCrumbs","setStreamHeight","Find","Store",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){return function(c){var e,f,o,v,w=g,x=d("activity_stream"),y=j,z=b.path().replace(/^\//,"").split("/")[0],A=c.scope,B=u("CurrentSearchParams"),C=c&&c.inventory_name?c.inventory_name:null,D=c&&c.url?c.url:null;a.flashMessage=null,D?x=D:"/home"!==b.path()&&(e="inventories"===z?"inventory":z.replace(/s$/,""),f=b.path().split("/"),f.splice(0,1),f.length>1&&/^\d+/.test(f[f.length-1])?(e=f[f.length-2],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?"+e+"__id="+f[f.length-1]):f.length>1?(e=f[f.length-1],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?or__object1="+e+"&or__object2="+e):x+="?or__object1="+e+"&or__object2="+e),$("#tab-content-container").append('
'),r(),C&&(o=t({list:a.breadcrumbs,key:"title",val:"{{ inventory_name }}"}),o&&(o.title=C)),l(),v=y.inject(w,{mode:"edit",id:"stream-content",searchSize:"col-lg-3",secondWidget:!0,activityStream:!0}),v.streamTitle=c&&c.title?c.title:null,v.closeStream=function(a){m(),v.searchCleanup&&v.searchCleanup(),B&&h({scope:A,set:B.set,list:B.list,url:B.defaultUrl,iterator:B.iterator,sort_order:B.sort_order,setWidgets:!1}),a&&b.path(a)},v.refreshStream=function(){v.search(w.iterator)},v.showDetail=function(a){q({scope:v,activity_id:a})},v.removeStreamPostRefresh&&v.removeStreamPostRefresh(),v.removeStreamPostRefresh=v.$on("PostRefresh",function(){var a,b,c,d,e,f;for(a=0;a'+v.activities[a].summary_fields.actor.username+"":"system",d=/^\_delete/,e=v.activities[a].object1,f=v.activities[a].object2,e&&v.activities[a].summary_fields[e]&&v.activities[a].summary_fields[e].name?d.test(v.activities[a].summary_fields[e].name)?v.activities[a].objects=v.activities[a].summary_fields[e].name:(c=p(v.activities[a].summary_fields.object1),v.activities[a].objects=''+v.activities[a].summary_fields[e].name+""):v.activities[a].object1&&(v.activities[a].objects=v.activities[a].object1),f&&v.activities[a].summary_fields[f]&&v.activities[a].summary_fields[f].name?d.test(v.activities[a].summary_fields.object2.name)?v.activities[a].objects+=","+v.activities[a].summary_fields[f].name:(c=p(v.activities[a].summary_fields.object2),v.activities[a].objects+=', '+v.activities[a].summary_fields[f].name+""):v.activities[a].object2&&(v.activities[a].objects+=", "+v.activities[a].object2),n(v.activities[a]);setTimeout(function(){s()},500)}),h({scope:v,set:w.name,list:w,url:x}),i({scope:v,list:w,url:x}),v.search(w.iterator)}}]),angular.module("AuthService",["ngCookies","Utilities"]).factory("Authorization",["$http","$rootScope","$location","$cookieStore","GetBasePath",function(a,b,c,d,e){return{setToken:function(a,c){d.remove("token"),d.remove("token_expires"),d.remove("userLoggedIn"),d.put("token",a),d.put("token_expires",c),d.put("userLoggedIn",!0),d.put("sessionExpired",!1),b.token=a,b.userLoggedIn=!0,b.token_expires=c,b.sessionExpired=!1},isUserLoggedIn:function(){return void 0===b.userLoggedIn&&(b.userLoggedIn=d.get("userLoggedIn"),b.sessionExpired=d.get("sessionExpired")),b.userLoggedIn},getToken:function(){return b.token?b.token:d.get("token")},retrieveToken:function(b,c){return a({method:"POST",url:e("authtoken"),data:{username:b,password:c}})},logout:function(){var a=angular.element(document.getElementById("main-view")).scope();a.$destroy(),b.$destroy(),d.remove("accordions"),d.remove("token"),d.remove("token_expires"),d.remove("current_user"),d.remove("lastPath"),d.put("userLoggedIn",!1),d.put("sessionExpired",!1),d.remove("lastPath","/home"),b.current_user={},b.license_tested=void 0,b.userLoggedIn=!1,b.sessionExpired=!1,b.token=null,b.token_expires=null,b.lastPath="/home"},getLicense:function(){return a({method:"GET",url:e("config"),headers:{Authorization:"Token "+this.getToken()}})},setLicense:function(a){a.tested=!1,d.put("license",a)},licenseTested:function(){var a,c;return void 0!==b.license_tested?c=b.license_tested:(a=d.get("license"),c=a&&void 0!==a.tested?a.tested:!1),c},getUser:function(){return a({method:"GET",url:"/api/v1/me/",headers:{Authorization:"Token "+this.getToken()}})},setUserInfo:function(a){b.current_user=a.results[0],d.put("current_user",a.results[0])},restoreUserInfo:function(){b.current_user=d.get("current_user")},getUserInfo:function(a){var c;return b.current_user?b.current_user[a]:(this.restoreUserInfo(),c=d.get("current_user"),c[a])}}}]),angular.module("InventoryTree",["Utilities","RestServices","GroupsHelper","PromptDialog"]).factory("SortNodes",[function(){return function(a){var b,c,d=[],e=[];for(b=0;b0?!0:!1,has_inventory_sources:s[e].has_inventory_sources,id:r,source:s[e].summary_fields.inventory_source.source,group_id:s[e].id,event_level:c,children:i,ngicon:s[e].children.length>0?"fa fa-minus-square-o node-toggle":"fa fa-square-o node-no-toggle",ngclick:"toggle("+r+")",related:{children:s[e].children.length>0?s[e].related.children:"",inventory_source:s[e].related.inventory_source},status:s[e].summary_fields.inventory_source.status,status_class:k["class"],status_tooltip:k.tooltip,launch_tooltip:k.launch_tip,launch_class:k.launch_class,hosts_status_tip:n.tooltip,show_failures:n.failures,hosts_status_class:n["class"],selected_class:"",show:!0,isDraggable:!0,isDroppable:!0},q.push(o),p&&o.group_id===p&&(m.selected_tree_id=r,m.selected_group_id=o.group_id),s[e].children.length>0&&j(s[e].children,r,c+1)}}function k(){e("start"),a.setUrl(b("inventory")+l+"/"),a.get().success(function(a){m.$emit("buildAllGroups",a.name,a.related.tree,a.related.groups)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+l+". GET returned: "+b})})}var l=h.inventory_id,m=h.scope,n=h.refresh,o=h.emit,p=h.new_group_id,q=[],r=1;m.buildAllGroupsRemove&&m.buildAllGroupsRemove(),m.buildAllGroupsRemove=m.$on("buildAllGroups",function(b,d,f){a.setUrl(f),a.get().success(function(a){i(a),j(a,0,0),m.autoShowGroupHelp=0===a.length?!0:!1,n?(m.groups=q,m.$emit("GroupTreeRefreshed",d,q,o)):m.$emit("GroupTreeLoaded",d,q,o)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory tree for: "+l+". GET returned: "+b})})}),k()}}]).factory("UpdateGroup",["ApplyEllipsis","GetSyncStatusMsg","Empty",function(a,b,c){return function(d){var e,f,g,h,i,j=d.scope,k=d.group_id,l=d.properties;for(e=0;e\n',m+='
\n',m+='
\n',m+='
\n',m+='\n',m+=1===k.id||0===l.parent?"
Move Group
\n":"
Copy or Move?
\n",m+="
\n",m+='
\n',1===k.id?m+="
Are you sure you want to move group "+l.name+" to the top level?
":0===l.parent?m+="
Are you sure you want to move group "+l.name+" from the top level and make it a child of "+k.name+"?
":(m+='
\n',m+="
Would you like to copy or move group "+l.name+" to group "+k.name+"?
\n",m+="\n",i=angular.element(document.getElementById("inventory-modal-container")),i.empty().append(m),a(i)(j),$("#copy-prompt-modal").modal({backdrop:"static",keyboard:!0,show:!0}),j.moveGroup=function(){var a,b,i;$("#copy-prompt-modal").modal("hide"),e("start"),j.removeGroupRemove&&j.removeGroupRemove(),j.removeGroupRemove=j.$on("removeGroup",function(){l.parent>0?(i=d({list:j.groups,key:"id",val:l.parent}),a=h("base")+"groups/"+i.group_id+"/children/",f.setUrl(a),f.post({id:l.group_id,disassociate:1}).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to remove "+l.name+" from "+i.name+". POST returned status: "+b})})):j.$emit("GroupDeleteCompleted")}),a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id},f.setUrl(a),f.post(b).success(function(){j.$emit("removeGroup")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})},j.copyGroup=function(){$("#copy-prompt-modal").modal("hide"),e("start");var a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id};f.setUrl(a),f.post(b).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})}}}]).factory("CopyMoveHost",["$compile","Alert","ProcessErrors","Find","Wait","Rest","Empty","GetBasePath",function(a,b,c,d,e,f,g,h){return function(b){var g,i,j=b.scope,k=d({list:j.groups,key:"id",val:b.target_tree_id}),l=d({list:j.hosts,key:"id",val:b.host_id}),m=!1,n="";if(l.summary_fields.all_groups)for(i=0;i\n',n+='
URL must begin with ssh, http or https and may not contain '@'
\n"),p+='\n',b.chkPass&&(p+='
Password must be stronger
\n',p+='
\n',p+='
\n',p+='\n',p+="
\n",p+=k({hdr:"Password Complexity",content:'
A password with reasonable strength is required. As you type the password a progress bar will measure the strength. Sufficient strength is reached when the bar turns green.
Password strength is judged using the following:
Minimum 8 characters in length
\n
Contains a sufficient combination of the following items:\n
\n';for(b in this.form.actions)("all"===this.form.actions[b].mode||this.form.actions[b].mode===a.mode)&&(c+=this.button({btn:this.form.actions[b],action:b,toolbar:!0}));return c+="
\n");for(d in this.form.buttons)"object"==typeof this.form.buttons[d]&&(e=this.form.buttons[d],"save"===d&&(e.label="Save",e["class"]="btn-success"),"reset"===d&&(e.label="Reset",e["class"]="btn-default"),p+='\n");p+="
\n"),j=1,k=m.related[g].base?m.related[g].base:g,k=k.replace(/^\//,"");for(d in m.related[g].fields)j++,n+=i({list:m.related[g],fld:d,options:a,base:k});n+='
\n';for(b in f.fields)void 0!==f.fields[b].searchable&&f.fields[b].searchable!==!0||(void 0!==f.fields[b].searchWidget&&1!==f.fields[b].searchWidget||1!==c)&&f.fields[b].searchWidget!==c||(h+='
\n';
+for(j in t.actions)("all"===t.actions[j].mode||t.actions[j].mode===b.mode)&&(void 0===t.actions[j].basePaths||t.actions[j].basePaths&&t.actions[j].basePaths.indexOf(c)>-1)&&(s+=this.button({btn:t.actions[j],action:j,toolbar:!0}));"select"===b.mode&&t.selectInstructions&&(k={awPopOver:t.selectInstructions,dataPlacement:"top",dataContainer:"body","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Help",iconSize:"fa-lg"},s+=this.button({btn:k,action:"help",toolbar:!0})),s+="
\n');for(n in t.fields)void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+='
\n"),o=2,c=t.base?t.base:t.name,c=c.replace(/^\//,"");for(n in t.fields)o++,void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+=h({list:t,fld:n,options:b,base:c}));if("select"===b.mode||"lookup"===b.mode)s+='
\n"),"groups"!==t.name&&(s+=e("lookup"===b.mode||b.id&&"form-modal-body"===b.id?{set:t.name,iterator:t.iterator}:{set:t.name,iterator:t.iterator})),s}}}]),angular.module("PromptDialog",["Utilities"]).factory("Prompt",[function(){return function(a){var b,c=angular.element(document.getElementById("prompt-modal")),d=c.scope();d.promptHeader=a.hdr,d.promptBody=a.body,d.promptAction=a.action,b=null===a["class"]||void 0===a["class"]?"btn-danger":a["class"],$("#prompt_action_btn").removeClass(b).addClass(b),$(c).modal({backdrop:"static",keyboard:!0,show:!0})}}]),String.prototype.strReverse=function(){var a,b="";for(a=0;aA credential must be associated with either a user or a team. Choosing a user allows only the selected user access to the credential. Choosing a team shares the credential with all team members.",dataTitle:"Owner",dataPlacement:"right",dataContainer:"body"},user:{label:"User that owns this credential",type:"lookup",sourceModel:"user",sourceField:"username",ngClick:"lookUpUser()",ngShow:"owner == 'user'",awRequiredWhen:{variable:"user_required",init:"false"}},team:{label:"Team that owns this credential",type:"lookup",sourceModel:"team",sourceField:"name",ngClick:"lookUpTeam()",ngShow:"owner == 'team'",awRequiredWhen:{variable:"team_required",init:"false"}},kind:{label:"Type",excludeModal:!0,type:"select",ngOptions:"kind.label for kind in credential_kind_options",ngChange:"kindChange()",addRequired:!0,editRequired:!0,helpCollapse:[{hdr:"Select a Credential Type",content:"
\n
AWS
\n
Access keys for Amazon Web Services used for inventory management or deployment.
\n
Machine
\n
Authentication for remote machine access. This can include SSH keys, usernames, passwords, and sudo information. Machine credentials are used when submitting jobs to run playbooks against remote hosts.
Rackspace
\n
Access information for Rackspace Cloud used for inventory management or deployment.
\n
SCM
\n
Used to check out and synchronize playbook repositories with a remote source control management system such as Git, Subversion (svn), or Mercurial (hg). These credentials are used on the Projects tab.
Click on the regions field to see a list of regions for your cloud provider. You can select multiple regions, or choose All to include all regions. Tower will only be updated with Hosts associated with the selected regions.
Override variables found in ec2.ini and used by the inventory update script. For a detailed description of these variables view ec2.ini in the Ansible github repo.
Enter variables using either JSON or YAML syntax. Use the radio button to toggle between the two.
If checked, all variables for child groups and hosts will be removed and replaced by those found on the external source.
When not checked a merge will be performed, combining local variables with those found on the external source.
",dataTitle:"Overwrite Variables",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"update_on_launch",label:"Update on Launch",type:"checkbox",ngShow:"source.value !== '' && source.value !== null",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this inventory, refresh the inventory from the selected source before executing job tasks.
",dataTitle:"Update on Launch",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{labelClass:"col-lg-3",controlClass:"col-lg-5",save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("HostGroupsFormDefinition",[]).value("HostGroupsForm",{editTitle:"Host Groups",name:"host",well:!1,formLabelSize:"col-lg-3",formFieldSize:"col-lg-9",fields:{groups:{label:"Groups",type:"select",multiple:!0,ngOptions:"group.name for group in inventory_groups",addRequired:!0,editRequired:!0,awPopOver:"
Provide a host name, ip address, or ip address:port. Examples include:
',dataTitle:"Inventory Variables",dataPlacement:"right",dataContainer:"body"}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{}}),angular.module("JobEventDataDefinition",[]).value("JobEventDataForm",{editTitle:"{{ id }} - {{ event_display }}",name:"job_events",well:!1,"class":"horizontal-narrow",fields:{event_data:{label:!1,type:"textarea",readonly:!0,rows:18,"class":"modal-input-xxlarge"}}}),angular.module("JobEventsFormDefinition",[]).value("JobEventsForm",{name:"job_events",well:!1,forceListeners:!0,fields:{status:{labelClass:"job-{{ status }}",type:"custom",section:"Event",control:'
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",awRequiredWhen:{variable:"playbookrequired",init:"true"},column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
The number of parallel or simultaneous processes to use while executing the playbook. 0 signifies the default value from the ansible configuration file.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
',dataTitle:"Limit",dataPlacement:"right",dataContainer:"body"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting the Tower server using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
Select the project containing the playbook you want this job to execute.
",dataTitle:"Project",dataPlacement:"right",dataContainer:"body"},playbook:{label:"Playbook",type:"select",ngOptions:"book for book in playbook_options",id:"playbook-select",addRequired:!0,editRequired:!0,column:1,awPopOver:"
Select the credential you want the job to use when accessing the remote hosts. Choose the credential containing the username and SSH key or password that Ansbile will need to log into the remote hosts.
Selecting an optional cloud credential in the job template will pass along the access credentials to the running playbook, allowing provisioning into the cloud without manually passing parameters to the included modules.
Provide a host pattern to further constrain the list of hosts that will be managed or affected by the playbook. Multiple patterns can be separated by ; : or ,
For more information and examples see the Selecting Targets section under Inventory and Patterns in the Ansible documentation.
',dataContainer:"body",dataTitle:"Limit",dataPlacement:"right"},verbosity:{label:"Verbosity",type:"select",ngOptions:"v.label for v in verbosity_options","default":0,addRequired:!0,editRequired:!0,column:1,awPopOver:"
Control the level of output ansible will produce as the playbook executes.
Pass extra command line variables to the playbook. This is the -e or --extra-vars command line parameter for ansible-playbook. Provide key/value pairs using either YAML or JSON.
Tags are useful when you have a large playbook, and you want to run a specific part of a play or task.
For example, you might have a task consisiting of a long list of actions. Tag values can be assigned to each action. Suppose the actions have been assigned tag values of "configuration", "packages" and "install".
If you just want to run the "configuration" and "packages" actions, you would enter the following here in the Job Tags field:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
Using this URL a host can contact Tower and request a configuration update using the job template. The request from the host must be a POST. Here is an example using curl:
Note the requesting host must be defined in your inventory. If ansible fails to locate the host either by name or IP address in one of your defined inventories, the request will be denied.
Successful requests will result in an entry on the Jobs tab, where the results and history can be viewed.
When contacting Tower using the callback URL, the calling host must authenticate by including this key in the POST data of the request. Here\'s an example using curl:
A project must have at least one organization. Pick one organization now to create the project, and then after the project is created you can add additional organizations.
Only super users and organization administrators are allowed to make changes to projects. Associating one or more organizations to a project determins which organizations admins have access to modify the project.",dataTitle:"Organization",dataContainer:"body",dataPlacement:"right"},scm_type:{label:"SCM Type",type:"select",ngOptions:"type.label for type in scm_type_options",ngChange:"scmChange()",addRequired:!0,editRequired:!0},missing_path_alert:{type:"alertblock","class":"alert-info",ngShow:"showMissingPlaybooksAlert && scm_type.value == ''",alertTxt:'
WARNING: There are no unassigned playbook directories in the base project path {{ base_dir }}. Either the projects directory is empty, or all of the contents are already assigned to other projects. New projects can be checked out from source control by changing the SCM type option rather than specifying checkout paths manually. To continue with manual setup, log into the Tower host and ensure content is present in a subdirectory under {{ base_dir }}. Run "chown -R awx" on the content directory to ensure Tower can read the playbooks.
',closeable:!1},base_dir:{label:"Project Base Path",type:"textarea",showonly:!0,ngShow:"scm_type.value == ''",awPopOver:"
Base path used for locating playbooks. Directories found inside this path will be listed in the playbook directory drop-down. Together the base path and selected playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
",dataTitle:"Project Base Path",dataContainer:"body",dataPlacement:"right"},local_path:{label:"Playbook Directory",type:"select",id:"local-path-select",ngOptions:"path.label for path in project_local_paths",awRequiredWhen:{variable:"pathRequired",init:!1},ngShow:"scm_type.value == '' && !showMissingPlaybooksAlert",awPopOver:"
Select from the list of directories found in the base path.Together the base path and the playbook directory provide the full path used to locate playbooks.
Use PROJECTS_ROOT in your environment settings file to determine the base path value.
Note: If using SSH protocol for GitHub or Bitbucket, enter in the SSH key only, do not enter a username (other than git). Additionally, GitHub and Bitbucket do not support password authentication when using SSH protocol. GIT read only protocol (git://) does not use username or password information.',show:"scm_type.value == 'git'"},{hdr:"SVN URLs",content:'
Note: Mercurial does not support password authentication for SSH. If applicable, add the username, password and key below. Do not put the username and key in the URL. If using Bitbucket and SSH, do not supply your Bitbucket username.',show:"scm_type.value == 'hg'"}]},scm_branch:{labelBind:"scmBranchLabel",type:"text",ngShow:"scm_type && scm_type.value !== ''",addRequired:!1,editRequired:!1},credential:{label:"SCM Credential",type:"lookup",ngShow:"scm_type && scm_type.value !== ''",sourceModel:"credential",sourceField:"name",ngClick:"lookUpCredential()",addRequired:!1,editRequired:!1},checkbox_group:{label:"SCM Update Options",type:"checkbox_group",ngShow:"scm_type && scm_type.value !== ''",fields:[{name:"scm_clean",label:"Clean",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Remove any local modifications prior to performing an update.
",dataTitle:"SCM Clean",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_delete_on_update",label:"Delete on Update",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Delete the local repository in its entirety prior to performing an update.
Depending on the size of the repository this may significantly increase the amount of time required to complete an update.
",dataTitle:"SCM Delete",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"},{name:"scm_update_on_launch",label:"Update on Launch",type:"checkbox",addRequired:!1,editRequired:!1,awPopOver:"
Each time a job runs using this project, perform an update to the local repository prior to starting the job.
",dataTitle:"SCM Update",dataContainer:"body",dataPlacement:"right",labelClass:"checkbox-options"}]}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{add:{ngClick:"add('organizations')",icon:"icon-plus",label:"Add",awToolTip:"Add an organization"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('organizations', organization.id, organization.name)",icon:"icon-edit",awToolTip:"Edit the organization","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('organizations', organization.id, organization.name, 'organizations')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the organization"}}}}}),angular.module("TeamFormDefinition",[]).value("TeamForm",{addTitle:"Create Team",editTitle:"{{ name }}",name:"team",well:!1,collapse:!0,collapseTitle:"Properties",collapseMode:"edit",collapseOpen:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{name:{label:"Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!1},description:{label:"Description",type:"text",addRequired:!1,editRequired:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",awRequiredWhen:{variable:"teamrequired",init:"true"}}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",add:"Add a new credential"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Modify the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{add:{ngClick:"add('projects')",icon:"icon-plus",label:"Add"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('projects', project.id, project.name)",icon:"icon-edit",awToolTip:"Modify the project","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('projects', project.id, project.name, 'projects')",icon:"icon-trash","class":"btn-danger",awToolTip:"Remove the project"}}},users:{type:"collection",title:"Users",iterator:"user",open:!1,actions:{add:{ngClick:"add('users')",icon:"icon-plus",label:"Add",awToolTip:"Add a user"}},fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('users', user.id, user.username)",icon:"icon-edit",awToolTip:"Edit user","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('users', user.id, user.username, 'users')",icon:"icon-terash","class":"btn-danger",awToolTip:"Remove user"}}}}}),angular.module("UserFormDefinition",[]).value("UserForm",{addTitle:"Create User",editTitle:"{{ username }}",name:"user",well:!1,forceListeners:!0,collapse:!0,collapseTitle:"Properties",collapseMode:"edit",collapseOpen:!0,actions:{stream:{"class":"btn-primary btn-xs activity-btn",ngClick:"showActivity()",awToolTip:"View Activity Stream",dataPlacement:"top",icon:"icon-comments-alt",mode:"edit",iconSize:"large"}},fields:{first_name:{label:"First Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},last_name:{label:"Last Name",type:"text",addRequired:!0,editRequired:!0,capitalize:!0},email:{label:"Email",type:"email",addRequired:!0,editRequired:!0,autocomplete:!1},organization:{label:"Organization",type:"lookup",sourceModel:"organization",sourceField:"name",ngClick:"lookUpOrganization()",excludeMode:"edit",awRequiredWhen:{variable:"orgrequired",init:!0}},username:{label:"Username",type:"text",awRequiredWhen:{variable:"not_ldap_user",init:!0},autocomplete:!1},password:{label:"Password",type:"password",ngShow:"ldap_user == false",addRequired:!0,editRequired:!1,ngChange:"clearPWConfirm('password_confirm')",autocomplete:!1,chkPass:!0},password_confirm:{label:"Confirm Password",type:"password",ngShow:"ldap_user == false",addRequired:!1,editRequired:!1,awPassMatch:!0,associated:"password",autocomplete:!1},is_superuser:{label:"Superuser (User has full system administration privileges.)",type:"checkbox",trueValue:"true",falseValue:"false","default":"false",ngShow:"current_user['is_superuser'] == true"},ldap_user:{label:"Created by LDAP",type:"checkbox",readonly:!0}},buttons:{save:{ngClick:"formSave()",ngDisabled:!0},reset:{ngClick:"formReset()",ngDisabled:!0}},related:{credentials:{type:"collection",title:"Credentials",iterator:"credential",open:!1,actions:{add:{ngClick:"add('credentials')",icon:"icon-plus",label:"Add",awToolTip:"Add a credential for this user"}},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('credentials', credential.id, credential.name)",icon:"icon-edit",awToolTip:"Edit the credential","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('credentials', credential.id, credential.name, 'credentials')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the credential"}}},permissions:{type:"collection",title:"Permissions",iterator:"permission",open:!1,actions:{add:{ngClick:"add('permissions')",icon:"icon-plus",label:"Add",awToolTip:"Add a permission for this user",ngShow:"PermissionAddAllowed"}},fields:{name:{key:!0,label:"Name",ngClick:"edit('permissions', permission.id, permission.name)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},fieldActions:{edit:{label:"Edit",ngClick:"edit('permissions', permission.id, permission.name)",icon:"icon-edit",awToolTip:"Edit the permission","class":"btn btn-default"},"delete":{label:"Delete",ngClick:"delete('permissions', permission.id, permission.name, 'permissions')",icon:"icon-trash","class":"btn-danger",awToolTip:"Delete the permission",ngShow:"PermissionAddAllowed"}}},admin_of_organizations:{type:"collection",title:"Admin of Organizations",iterator:"adminof",open:!1,base:"/organizations",actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},organizations:{type:"collection",title:"Organizations",iterator:"organization",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},teams:{type:"collection",title:"Teams",iterator:"team",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}},projects:{type:"collection",title:"Projects",iterator:"project",open:!1,actions:{},fields:{name:{key:!0,label:"Name"},description:{label:"Description"}}}}}),angular.module("InventoryGroupsHelpDefinition",[]).value("InventoryGroupsHelp",{story:{hdr:"Building your inventory",width:510,height:560,steps:[{intro:"Start by creating a group:",img:{src:"groups001.png",maxWidth:338,maxHeight:222},box:'Click on the groups list (the left side of the page) to add a new group.',autoOffNotice:!0},{intro:"Enter group properties:",img:{src:"groups002.png",maxWidth:443,maxHeight:251},box:'Enter the group name, a description and any inventory variables. Variables can be entered using either JSON or YAML syntax. For more on inventory variables, see docs.ansible.com/intro_inventory.html'},{intro:"Cloud inventory: select cloud source",img:{src:"groups003.png",maxWidth:412,maxHeight:215},box:'For a cloud inventory, choose the cloud provider from the list and select your credentials. If you have not already setup credentials for the provider, you will need to do that first on the Credentials tab.'},{intro:"Cloud inventory: synchronize Tower with the cloud",img:{src:"groups004.png",maxWidth:261,maxHeight:221},box:'To pull the cloud inventory into Tower, initiate an inventory sync by clicking .'},{intro:"Groups can have subgroups:",img:{src:"groups005.png",maxWidth:430,maxHeight:206},box:'
First, select a group. Then click to create a new group. The new group will be added to the selected group.
'},{intro:"Copy or move groups:",img:{src:"groups006.png",maxWidth:263,maxHeight:211},box:'
Copy or move a group by dragging and dropping its name onto another group name. A dialog will appear asking if the group should be coppied or moved.
Your Ansible Tower license has reached capacity for the number of managed hosts allowed. You will not be able to add any additional hosts.
"+i,c(d,f,g,null,!0)))}}]),angular.module("ChildrenHelper",["RestServices","Utilities"]).factory("ToggleChildren",[function(){return function(a){function b(a){var b;for(i[a].ngicon="fa fa-minus-square-o node-toggle",b=a+1;b10?10:i,i=3>i?3:i,f.fields[h].rows=i);break;case"results":if(a.event_data&&a.event_data.res&&void 0===a.event_data.res[h])delete f.fields[h];else if(Array.isArray(a.event_data.res[h])&&0!==a.event_data.res[h].length){for(j="",c=0;c10?10:i,i=3>i?3:i,f.fields[h].rows=i)}else delete f.fields[h];break;case"module_name":case"module_args":a.event_data&&a.event_data.res&&(void 0===a.event_data.res.invocation||void 0===a.event_data.res.invocation[h])&&delete f.fields[h]}b=d.inject(f,{mode:"edit",modal:!0,related:!1}),d.reset(),b.formModalAction=function(){$("#form-modal").modal("hide")},b.formModalActionLabel="OK",b.formModalCancelShow=!1,b.formModalInfo="View JSON",$("#form-modal .btn-success").removeClass("btn-success").addClass("btn-none"),$("#form-modal").addClass("skinny-modal"),b.formModalHeader=a.event_display.replace(/^\u00a0*/g,""),b.formModalInfoAction=function(){var b=g,c=b.inject(l,{mode:"edit",modal:!0,related:!1,modal_selector:"#form-modal2",modal_body_id:"form-modal2-body",modal_title_id:"formModal2Header"});b.reset(),c.formModal2Header=a.event_display.replace(/^\u00a0*/g,""),c.event_data=JSON.stringify(a.event_data,null," "),c.formModal2ActionLabel="OK",c.formModal2CancelShow=!1,c.formModal2Info=!1,c.formModalInfo="View JSON",c.formModal2Action=function(){$("#form-modal2").modal("hide")},$("#form-modal2 .btn-success").removeClass("btn-success").addClass("btn-none")},"string"==typeof a.event_data.res&&(b.traceback=a.event_data.res);for(h in f.fields)switch(h){case"status":b.status=a.failed?"error":a.changed?"changed":"success";break;case"created":n=new Date(a.created),b.created=k(n);break;case"host":a.summary_fields&&a.summary_fields.host&&(b.host=a.summary_fields.host.name);break;case"id":case"task":case"play":b[h]=a[h];break;case"start":case"end":a.event_data&&a.event_data.res&&!m(a.event_data.res[h])&&(b[h]=a.event_data.res[h]);break;case"results":if(Array.isArray(a.event_data.res[h])&&a.event_data.res[h].length>0){for(j="",c=0;c button.',"alert-info"):(f("start"),a.setUrl(l.related.inventory_source),a.get().success(function(a){var b=a.related.current_update?a.related.current_update:a.related.last_update;d({group_name:a.summary_fields.group.name,last_update:b,license_error:a.summary_fields.last_update&&a.summary_fields.last_update.license_error?!0:!1,tree_id:j,group_id:k,parent_scope:i})}).error(function(a,c){f("stop"),b(i,a,c,null,{hdr:"Error!",msg:"Failed to retrieve inventory source: "+l.related.inventory_source+" POST returned status: "+c})})))}}]).factory("GetHostsStatusMsg",[function(){return function(a){var b,c,d,e=a.active_failures,f=a.total_hosts;return e>0?(b=f+(1===f?" host":" hosts")+". "+e+" with failed jobs.",d="true",c=!0):(c=!1,0===f?(b="Group contains 0 hosts.",d="na"):(b=f+(1===f?" host":" hosts")+". No job failures",d="false")),{tooltip:b,failures:c,"class":d}}}]).factory("GetSyncStatusMsg",[function(){return function(a){var b,c,d,e=a.status,f="",g="Start sync process";switch(b=e,c="icon-cloud-"+b,e){case"never updated":b="never",c="icon-cloud-na disabled",d='Sync not performed. Click to start it now.';break;case"none":case"":f="btn-disabled",b="n/a",c="icon-cloud-na disabled",d='Cloud source not configured. Click to update.',g=d;break;case"failed":d="Sync failed. Click to view log.";break;case"successful":d="Sync completed. Click to view log.";break;case"updating":d="Sync running"}return{"class":c,tooltip:d,status:b,launch_class:f,launch_tip:g}}}]).factory("SourceChange",["GetBasePath","CredentialList","LookUpInit","Empty",function(a,b,c,d){return function(e){var f,g,h=e.scope,i=e.form;d(h.source)||("file"===h.source.value?h.sourcePathRequired=!0:(h.sourcePathRequired=!1,h.source_path="",h[i.name+"_form"].source_path.$setValidity("required",!0)),"rax"===h.source.value?(h.source_region_choices=h.rax_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])):"ec2"===h.source.value&&(h.source_region_choices=h.ec2_regions,$("#s2id_group_source_regions").select2("data",[{id:"all",text:"All"}])),("rax"===h.source.value||"ec2"===h.source.value)&&(f="rax"===h.source.value?"rax":"aws",g=a("credentials")+"?cloud=true&kind="+f,c({url:g,scope:h,form:i,list:b,field:"credential"})))}}]).factory("GroupsCancelUpdate",["Rest","ProcessErrors","Alert","Wait","Find",function(a,b,c,d,e){return function(f){var g,h=f.scope,i=f.tree_id;h.removeCancelUpdate&&h.removeCancelUpdate(),h.removeCancelUpdate=h.$on("CancelUpdate",function(e,f){a.setUrl(f),a.post().success(function(){d("stop"),c("Inventory Sync Cancelled",'Your request to cancel the sync process was submitted to the task manger. Click the button to monitor the status.',"alert-info")}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+f+" failed. POST status: "+c})})}),h.removeCheckCancel&&h.removeCheckCancel(),h.removeCheckCancel=h.$on("CheckCancel",function(e,f,g){var i=g?g:f;i+="cancel/",a.setUrl(i),a.get().success(function(a){a.can_cancel?h.$emit("CancelUpdate",i):(d("stop"),c("Cancel Inventory Sync",'Either you do not have access or the sync process completed. Click the button to view the latest status.',"alert-info"))}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+i+" failed. GET status: "+c})})}),g=e({list:h.groups,key:"id",val:i}),h.selected_tree_id=g.id,h.selected_group_id=g.group_id,!g||"updating"!==g.status&&"pending"!==g.status?c("Cancel Inventory Sync",'The sync process completed. Click the to view the latest status.',"alert-info"):(d("start"),a.setUrl(g.related.inventory_source),a.get().success(function(a){h.$emit("CheckCancel",a.related.last_update,a.related.current_update)}).error(function(a,c){d("stop"),b(h,a,c,null,{hdr:"Error!",msg:"Call to "+g.related.inventory_source+" failed. GET status: "+c})}))}}]).factory("GroupsAdd",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","ParseTypeChange","GroupsEdit","Wait","GetChoices","GetSourceTypeOptions","LookUpInit","BuildTree","SourceChange","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){return function(b){var c,d=b.inventory_id,i=void 0!==b.group_id?b.group_id:null,m=b.scope,q=null!==i?k("groups")+i+"/children/":k("inventory")+d+"/groups/",u=g,v=h,w=v.inject(u,{mode:"add",modal:!0,related:!1,show_modal:!1});$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),w.formModalActionLabel="Save",w.formModalCancelShow=!0,w.parseType="yaml",w.source=null,l(w),v.reset(),w.removeAddTreeRefreshed&&w.removeAddTreeRefreshed(),w.removeAddTreeRefreshed=w.$on("GroupTreeRefreshed",function(){a.formModalHeader=null,a.formModalCancleShow=null,a.formModalActionLabel=null,n("stop"),$("#form-modal").modal("hide"),w.removeAddTreeRefreshed()}),w.removeSaveComplete&&w.removeSaveComplete(),w.removeSaveComplete=w.$on("SaveComplete",function(a,b,c){c||(w.searchCleanup&&w.searchCleanup(),w.formModalActionDisabled=!1,r({scope:m,inventory_id:d,refresh:!0,new_group_id:b}),t())}),w.removeFormSaveSuccess&&w.removeFormSaveSuccess(),w.removeFormSaveSuccess=w.$on("formSaveSuccess",function(a,b,c){var d,g,h,i,k=!1,l={};if(null!==w.source.value&&""!==w.source.value){for(l.group=b,l.source=w.source.value,l.source_path=w.source_path,l.credential=w.credential,l.overwrite=w.overwrite,l.overwrite_vars=w.overwrite_vars,l.update_on_launch=w.update_on_launch,d=$("#s2id_group_source_regions").select2("data"),g=[],h=0;h"+A.summary_fields.group.name+". Use the Refresh button to monitor the status.","alert-info"):o({scope:A,group_id:d,url:A.group_update_url,group_name:A.name,group_source:A.source.value})},A.sourceChange=function(){v({scope:A,form:g})}}}]).factory("GroupsDelete",["$rootScope","$location","$log","$routeParams","Rest","Alert","GroupForm","GenerateForm","Prompt","ProcessErrors","GetBasePath","Wait","BuildTree","Find",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){return function(a){var b,c=a.scope,d=a.tree_id,f=a.inventory_id,g=n({list:c.groups,key:"id",val:d}),h=k("inventory")+f+"/groups/";b=function(){$("#prompt-modal").on("hidden.bs.modal",function(){l("start")}),$("#prompt-modal").modal("hide"),e.setUrl(h),e.post({id:g.group_id,disassociate:1}).success(function(){$("#prompt-modal").off(),c.$emit("GroupDeleteCompleted")}).error(function(a,b){l("stop"),j(c,a,b,null,{hdr:"Error!",msg:"Call to "+h+" failed. POST returned status: "+b})})},i({hdr:"Delete Group",body:"
Are you sure you want to delete group "+g.name+"?
",action:b,"class":"btn-danger"})}}]).factory("ShowUpdateStatus",["$rootScope","$location","$log","$routeParams","Rest","Alert","GenerateForm","Prompt","ProcessErrors","GetBasePath","FormatDate","InventoryStatusForm","Wait","Empty","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){return function(a){function b(a){var b,d;return b=a.match(/\n/g),d=b?b.length:1,d>c?c:d}var c,d,h,j,n,p,q,r=a.group_name,s=a.last_update,t=g,u=l,v=a.license_error;void 0===s||null===s||""===s?(m("stop"),f("Missing Configuration","The selected group is not configured for inventory sync. Edit the group and provide Source information.","alert-info")):(d='
\n
\n',$("#inventory-modal-container").empty().append(d),h=t.inject(u,{mode:"edit",id:"form-container",breadCrumbs:!1,related:!1}),j=$(document).width(),n=$("body").height(),j>1199?(p=675,q=750>n?n-20:750,c=18):1199>=j&&j>=768?(p=550,q=620>n?n-15:620,c=12):(p=j-20,q=500>n?n:500,c=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:p,height:q,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#inventory-modal-container").empty(),o()},open:function(){m("stop")}}),e.setUrl(s),e.get().success(function(a){for(var c in u.fields)a[c]&&(h[c]="created"===c?k(new Date(a[c])):a[c]);h.license_error=v,h.status_rows=b(a.status),h.stdout_rows=b(a.result_stdout),h.traceback_rows=b(a.result_traceback),$("#status-modal-dialog").dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(h,a,b,null,{hdr:"Error!",msg:"Failed to retrieve last update: "+s+". GET status: "+b})}))}}]),angular.module("HostsHelper",["RestServices","Utilities","ListGenerator","HostListDefinition","SearchHelper","PaginationHelpers","ListGenerator","AuthService","HostsHelper","InventoryHelper","RelatedSearchHelper","InventoryFormDefinition","SelectionHelper","HostGroupsFormDefinition"]).factory("SetEnabledMsg",[function(){return function(a){a.enabledToolTip=a.has_inventory_sources?a.enabled?"Host is available":"Host is not available":a.enabled?"Host is available. Click to toggle.":"Host is not available. Click to toggle."}}]).factory("SetHostStatus",["SetEnabledMsg",function(a){return function(b){b.activeFailuresLink="/#/hosts/"+b.id+"/job_host_summaries/?inventory="+b.inventory+"&host_name="+encodeURI(b.name),b.has_active_failures===!0?(b.badgeToolTip="Most recent job failed. Click to view jobs.",b.active_failures="failed"):b.has_active_failures===!1&&null===b.last_job?(b.has_active_failures="none",b.badgeToolTip="No job data available.",b.active_failures="n/a"):b.has_active_failures===!1&&null!==b.last_job&&(b.badgeToolTip="Most recent job successful. Click to view jobs.",b.active_failures="success"),b.enabled_flag=b.enabled,a(b)}}]).factory("SetStatus",["SetEnabledMsg","Empty",function(a,b){return function(c){function d(a){return a.length>25?a.substr(0,25)+"...":a}function e(a){var b,c,e;if(a.has_active_failures===!0||a.has_active_failures===!1&&null!==a.last_job)if(a.has_active_failures===!0?(a.badgeToolTip="Most recent job failed. Click to view jobs.",a.active_failures="failed"):(a.badgeToolTip="Most recent job successful. Click to view jobs.",a.active_failures="success"),a.summary_fields.recent_jobs.length>0){for(e=a.summary_fields.recent_jobs.sort(function(a,b){return-1*(a-b)}),h="Recent Jobs",g='
";else a.has_active_failures===!1&&null===a.last_job&&(a.has_active_failures="none",a.badgeToolTip="No job data available.",a.active_failures="n/a");a.job_status_html=g,a.job_status_title=h}var f,g,h,i=c.scope,j=c.host;if(b(j))for(f=0;fAre you sure you want to delete host "+j+" from group "+n.name+"?":"
\n",d=j("hosts")+l+"/",f=o.inject(null,{mode:"edit",modal:!0,related:!1,html:c}),b=0;bGroups',f.formModalCancelShow=!0,f.formModalActionDisabled=!0,$("#form-modal .btn-none").removeClass("btn-none").addClass("btn-success"),f.hostGroupChangeRemove&&f.hostGroupChangeRemove(),f.hostGroupChangeRemove=f.$on("hostGroupChange",function(){p.pop(),0===p.length&&(h=function(){setTimeout(function(){m("stop")},500)},k({scope:f,inventory_id:n,group_id:f.group_id,action:h}))}),f.formModalAction=function(){var a,b,c;for($("#form-modal").modal("hide"),m("start"),a=0;a0?(f.assignedGroups=null,f.leftButtonDisabled=!0,f.rightButtonDisabled=!1):f.rightButtonDisabled=!0},f.rightChange=function(){null!==f.assignedGroups&&f.assignedGroups.length>0?(f.selectedGroups=null,f.leftButtonDisabled=!1,f.rightButtonDisabled=!0):f.leftButtonDisabled=!0},f.moveLeft=function(){var a,b,c,d;for(a=0;af.available_groups[b].name.toLowerCase()&&f.assignedGroups[a].name.toLowerCase()f.host_groups[b].name.toLowerCase()&&f.selectedGroups[a].name.toLowerCase()0){for(j("stop"),u+='\n",m=angular.element(document.getElementById("password-body")),m.html(u),c(m.contents())(q),$("#password-modal").modal(),$("#password-modal").on("shown.bs.modal",function(){$("#password-body").find('input[type="password"]:first').focus()})}else q.startJob()}}]).factory("SubmitJob",["PromptPasswords","$compile","Rest","$location","GetBasePath","CredentialList","LookUpInit","CredentialForm","ProcessErrors","JobTemplateForm","Wait",function(a,b,c,d,e,f,g,h,i,j,k){return function(b){function l(b){var e,f,g;m.credentialWatchRemove&&m.credentialWatchRemove(),e=(new Date).toISOString(),f=b.related.jobs?b.related.jobs:b.related.job_template+"jobs/",g=o?o:b.name,k("start"),c.setUrl(f),c.post({name:g+" "+e,description:b.description,job_template:b.id,inventory:b.inventory,project:b.project,playbook:b.playbook,credential:b.credential,forks:b.forks,limit:b.limit,verbosity:b.verbosity,extra_vars:b.extra_vars}).success(function(b){m.job_id=b.id,b.passwords_needed_to_start.length>0?a({scope:m,passwords:b.passwords_needed_to_start,start_url:b.related.start,form:h}):(c.setUrl(b.related.start),c.post().success(function(){k("stop");var a=d.path().replace(/^\//,"").split("/")[0];"jobs"===a?m.refresh():d.path("/jobs")}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to start job. POST returned status: "+b})}))}).error(function(a,b){k("stop"),i(m,a,b,null,{hdr:"Error!",msg:"Failed to create job. POST returned status: "+b})})}var m=b.scope,n=b.id,o=b.template?b.template:null,p=d.path().replace(/^\//,"").split("/")[0],q=e(p)+n+"/";k("start"),c.setUrl(q),c.get().success(function(a){m.credential="",""===a.credential||null===a.credential?(k("stop"),m.credentialWatchRemove&&m.credentialWatchRemove(),m.credentialWatchRemove=m.$watch("credential",function(b,c){b!==c&&""!==m.credential&&null!==m.credential&&void 0!==m.credential&&(a.credential=m.credential,l(a))}),g({scope:m,form:j,current_item:null,list:f,field:"credential",hdr:"Credential Required"}),m.lookUpCredential()):l(a)}).error(function(a,b){i(m,a,b,null,{hdr:"Error!",msg:"Failed to get job template details. GET returned status: "+b})})}}]).factory("ProjectUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","ProjectsForm","Wait",function(a,b,c,d,e,f,g,h,i){return function(b){var d=b.scope,j=b.project_id,k=e("projects")+j+"/update/";d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(){i("stop"),g("Update Started","The request to start the SCM update process was submitted. To monitor the update status, refresh the page by clicking the Refresh button.","alert-info"),d.refresh()}),d.removeSCMSubmit&&d.removeSCMSubmit(),d.removeSCMSubmit=d.$on("SCMSubmit",function(b,c,e){a({scope:d,passwords:c,start_url:k,form:h,extra_html:e})}),i("start"),c.setUrl(k),c.get().success(function(a){var b,c;if(i("stop"),a.can_update){for(c="",b=0;b\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="\n",d.projects[b].scm_username&&(c+='
\n',c+='\n',c+='
\n',c+='",c+="
\n",c+="
\n");break}c+="",d.$emit("SCMSubmit",a.passwords_needed_to_update,c)}else g("Permission Denied","You do not have access to update this project. Please contact your system administrator.","alert-danger")}).error(function(a,b){f(d,a,b,null,{hdr:"Error!",msg:"Failed to get project update details: "+k+" GET status: "+b})})}}]).factory("InventoryUpdate",["PromptPasswords","$compile","Rest","$location","GetBasePath","ProcessErrors","Alert","GroupForm","BuildTree","Wait",function(a,b,c,d,e,f,g,h,i,j){return function(b){var d=b.scope,e=b.url,i=b.group_id,k=b.tree_id;d.removeHostReloadComplete&&d.removeHostReloadComplete(),d.removeHostReloadComplete=d.$on("HostReloadComplete",function(){j("stop"),g("Update Started",'Your request to start the inventory sync process was submitted. Monitor progress by clicking the button.',"alert-info"),d.removeHostReloadComplete&&d.removeHostReloadComplete()}),d.removeUpdateSubmitted&&d.removeUpdateSubmitted(),d.removeUpdateSubmitted=d.$on("UpdateSubmitted",function(a,b){"started"===b&&(d.refreshGroups?(d.selected_tree_id=k,d.selected_group_id=i,d.refreshGroups()):d.refresh&&d.refresh(),d.$emit("HostReloadComplete"))}),d.removeInventorySubmit&&d.removeInventorySubmit(),d.removeInventorySubmit=d.$on("InventorySubmit",function(b,c,f){a({scope:d,passwords:c,start_url:e,form:h,extra_html:f})}),j("start"),c.setUrl(e),c.get().success(function(a){a.can_update?d.$emit("InventorySubmit",a.passwords_needed_to_update):(j("stop"),g("Permission Denied","You do not have access to run the update. Please contact your system administrator.","alert-danger"))}).error(function(a,b){j("stop"),f(d,a,b,null,{hdr:"Error!",msg:"Failed to get inventory_source details. "+e+"GET status: "+b})})}}]),angular.module("JobsHelper",["Utilities","FormGenerator","JobSummaryDefinition","InventoryHelper"]).factory("JobStatusToolTip",[function(){return function(a){var b;switch(a){case"successful":case"success":b="There were no failed tasks.";break;case"failed":b="Some tasks encountered errors.";break;case"canceled":b="Stopped by user request.";break;case"new":b="In queue, waiting on task manager.";break;case"waiting":b="SCM Update or Inventory Update is executing.";break;case"pending":b="Not in queue, waiting on task manager.";break;case"running":b="Playbook tasks executing."}return b}}]).factory("ShowJobSummary",["Rest","Wait","GetBasePath","FormatDate","ProcessErrors","GenerateForm","JobSummary","WatchInventoryWindowResize",function(a,b,c,d,e,f,g,h){return function(i){function j(a){var b=a.match(/\n/g),c=b?b.length:1;return c>p?20:c}var k,l,m,n,o,p,q,r,s=i.job_id,t=f,u=g;r='
Only allow the user or team to view the inventory.
\n
Write
\n
Allow the user or team to modify hosts and groups contained in the inventory, add new hosts and groups, and perform inventory sync operations.\n
Admin
\n
Allow the user or team full access to the inventory. This includes reading, writing, deletion of the inventory and inventory sync operations.
\n
\n"):(b.projectrequired=!0,b.permissionTypeHelp="
\n
Run
\n
Allow the user or team to perform a live deployment of the project against the inventory. In Run mode modules will be executed, and changes to the inventory will occur.
\n
Check
\n
Only allow the user or team to deploy the project against the inventory as a dry-run operation. In Check mode, module operations will only be simulated. No changes will occur.
\n
\n"),c&&(b.permission_type="Inventory"===b.category?"read":"run")}}]),angular.module("ProjectPathHelper",["RestServices","Utilities"]).factory("GetProjectPath",["Alert","Rest","GetBasePath","ProcessErrors",function(a,b,c,d){return function(a){function e(a){var b,c,d=[],e=[];for(b=0;b\n',$("#projects-modal-container").empty().append(b),c=q.inject(r,{mode:"edit",id:"form-container",related:!1,breadCrumbs:!1}),q.reset(),d=$(document).width(),f=$("body").height(),d>1199?(h=675,j=750>f?f-20:750,n=20):1199>=d&&d>=768?(h=550,j=620>f?f-15:620,n=15):(h=d-20,j=500>f?f:500,n=10),$("#status-modal-dialog").dialog({buttons:{OK:function(){$(this).dialog("close")}},modal:!0,width:h,height:j,autoOpen:!1,create:function(){$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-titlebar button").empty().attr({"class":"close"}).text("x"),$('.ui-dialog[aria-describedby="status-modal-dialog"]').find(".ui-dialog-buttonset button:first").attr({"class":"btn btn-primary"})},resizeStop:function(){var a=$('.ui-dialog[aria-describedby="status-modal-dialog"]'),b=a.find("#status-modal-dialog");b.width(a.width()-28)},close:function(){$(".tooltip").each(function(){$(this).remove()}),$(".popover").each(function(){$(this).remove()}),$("#status-modal-dialog").dialog("destroy"),$("#projects-modal-container").empty()},open:function(){m("stop")}}),e.setUrl(p),e.get().success(function(a){var b,d=a;for(b in r.fields)d[b]?c[b]="created"===b?k(new Date(d[b])):d[b]:d.summary_fields.project[b]&&(c[b]=d.summary_fields.project[b]);$("#status-modal-dialog").dialog({title:d.summary_fields.project.name+" Status"}).dialog("open")}).error(function(a,b){$("#form-modal").modal("hide"),i(c,a,b,r,{hdr:"Error!",msg:"Failed to retrieve status of project: "+o+". GET status: "+b})})}}]),angular.module("SelectionHelper",["Utilities","RestServices"]).factory("SelectionInit",["Rest","Alert","ProcessErrors","ReturnToCaller","Wait",function(a,b,c,d,e){return function(b){var f,g=b.scope,h=b.list,i=b.url,j=b.returnToCaller;f=void 0!==b.selected?b.selected:[],g.formModalActionDisabled=!0,g.disableSelectBtn=!0,g["toggle_"+h.iterator]=function(a,b){var c,d,e;for(c=0;c0?(g.formModalActionDisabled=!1,g.disableSelectBtn=!1):(g.formModalActionDisabled=!0,g.disableSelectBtn=!0)},g.finishSelection=function(){function b(){f=[],void 0!==j?d(j):($("#form-modal").modal("hide"),g.$emit("modalClosed"))}function k(b){a.post(b).success(function(a,b){m.push({result:"success",data:a,status:b}),g.$emit("callFinished")}).error(function(a,b,c){m.push({result:"error",data:a,status:b,headers:c}),g.$emit("callFinished")})}a.setUrl(i);var l,m=[];if(g.formModalActionDisabled=!0,g.disableSelectBtn=!0,e("start"),g.callFinishedRemove&&g.callFinishedRemove(),g.callFinishedRemove=g.$on("callFinished",function(){var a,d=0;if(m.length===f.length){for(e("stop"),a=0;a0)for(l=0;lh)h++,setTimeout(1e3,e());else if("success"===g.status)return d(a)}var f,g={},h=0;return null===c.apiDefaults||void 0===c.apiDefaults?(f="/api/v1/",b.setUrl(f),b.get().success(function(a){var b,d=a;for(b in d)switch(b){case"organizations":d[b].iterator="organization";break;case"jobs":d[b].iterator="job";break;case"users":d[b].iterator="user";break;case"teams":d[b].iterator="team";break;case"hosts":d[b].iterator="host";break;case"groups":d[b].iterator="group";break;case"projects":d[b].iterator="project";break;case"inventories":d[b].iterator="inventory"}c.apiDefaults=d,g={status:"success"}}).error(function(a,b){g={status:"error",msg:"Call to "+f+" failed. GET returned status: "+b}}),e()):d(a)}}]),angular.module("InventoryHelper",["RestServices","Utilities","OrganizationListDefinition","ListGenerator","AuthService","InventoryHelper","InventoryFormDefinition","ParseHelper","SearchHelper"]).factory("WatchInventoryWindowResize",["ApplyEllipsis",function(a){return function(){var b;$(window).resize(function(){clearTimeout(b),b=setTimeout(function(){$("#groups_table .name-column").each(function(){var a=$(this).width(),b=$(this).find(".level").width(),c=parseInt($(this).find(".level").css("padding-left").replace(/px/,"")),d=b+c,e=100-Math.ceil(d/a*100)+"%";$(this).find(".group-name").css({width:e})}),a("#groups_table .group-name a"),a("#hosts_table .host-name a")},100)})}}]).factory("SaveInventory",["InventoryForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","Wait",function(a,b,c,d,e,f,g,h,i){return function(e){var f,h,j,k=e.scope,l=a,m=g("inventory");i("start");try{if(h="json"===k.inventoryParseType?JSON.parse(k.inventory_variables):jsyaml.load(k.inventory_variables),"object"!=typeof h)throw"failed to return an object!";j={};for(f in l.fields)"inventory_variables"!==f&&(l.fields[f].realName?j[l.fields[f].realName]=k[f]:j[f]=k[f]);b.setUrl(m+k.inventory_id+"/"),b.put(j).success(function(a){k.inventory_variables?(b.setUrl(a.related.variable_data),b.put(h).success(function(){i("stop"),k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory varaibles. PUT returned status: "+b})})):k.$emit("InventorySaved")}).error(function(a,b){d(k,a,b,l,{hdr:"Error!",msg:"Failed to update inventory. POST returned status: "+b})})}catch(n){i("stop"),c("Error","Error parsing inventory variables. Parser returned: "+n)}}}]).factory("EditInventoryProperties",["InventoryForm","GenerateForm","Rest","Alert","ProcessErrors","LookUpInit","OrganizationList","GetBasePath","ParseTypeChange","SaveInventory","Wait","Store","SearchInit",function(a,b,c,d,e,f,g,h,i,j,k,l,m){return function(n){var o,p=n.scope,q=n.inventory_id,r=b,s=a,t={},u=l("CurrentSearchParams");s.well=!1,o=r.inject(s,{mode:"edit",modal:!0,related:!1,modal_show:!1}),s.well=!0,i(o,"inventory_variables","inventoryParseType"),o.inventoryParseType="yaml",o.formModalActionLabel="Save",o.formModalCancelShow=!0,o.formModalInfo=!1,o.formModalHeader="Inventory Properties",k("start"),c.setUrl(h("inventory")+q+"/"),c.get().success(function(a){var b,c;for(b in s.fields){if("inventory_variables"===b){if($.isEmptyObject(a.variables)||"{}"===a.variables||"null"===a.variables||""===a.variables)o.inventory_variables="---";else try{c=JSON.parse(a.variables),o.inventory_variables=jsyaml.safeDump(c)}catch(e){d("Variable Parse Error","Attempted to parse variables for inventory: "+q+". Parse returned: "+e),console&&(console.log(e),console.log("data:"),console.log(a.variables)),o.inventory_variables="---"}t.inventory_variables=o.variables}else"inventory_name"===b?(o[b]=a.name,t[b]=o[b]):"inventory_description"===b?(o[b]=a.description,t[b]=o[b]):a[b]&&(o[b]=a[b],t[b]=o[b]);s.fields[b].sourceModel&&a.summary_fields&&a.summary_fields[s.fields[b].sourceModel]&&(o[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField],t[s.fields[b].sourceModel+"_"+s.fields[b].sourceField]=a.summary_fields[s.fields[b].sourceModel][s.fields[b].sourceField])}f({scope:o,form:s,current_item:o.organization,list:g,field:"organization"}),k("stop"),$("#form-modal").modal("show")}).error(function(a,b){e(o,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+q+". GET returned: "+b})}),o.removeInventorySaved&&o.removeInventorySaved(),o.removeInventorySaved=o.$on("InventorySaved",function(){$("#form-modal").modal("hide"),o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1}),p.$emit("RefreshInventories")}),o.cancelModal=function(){o.searchCleanp&&o.searchCleanup(),m({scope:p,set:u.set,list:u.list,url:u.defaultUrl,iterator:u.iterator,sort_order:u.sort_order,setWidgets:!1})},o.formModalAction=function(){p.inventory_id=q,p.inventory_name=o.inventory_name,j({scope:o})}}}]),angular.module("md5Helper",["RestServices","Utilities"]).factory("md5Setup",[function(){return function(a){var b=a.scope,c=a.master,d=a.check_field,e=a.default_val;b[d]=e,c[d]=e,b.genMD5=function(a){var c=new Date;b[a]=$.md5("AnsibleWorks"+c.getTime())},b.toggleCallback=function(a){"false"===b.allow_callbacks&&(b[a]="")},b.selectAll=function(a){$('input[name="'+a+'"]').focus().select()}}}]),angular.module("RefreshRelatedHelper",["RestServices","Utilities","PaginationHelpers"]).factory("RefreshRelated",["ProcessErrors","Rest","Wait","PageRangeSetup",function(a,b,c,d){return function(e){var f=e.scope,g=e.set,h=e.iterator,i=e.url;b.setUrl(i),b.get().success(function(a){d({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[g]=a.results,f[h+"Loading"]=!1,f[h+"HoldInput"]=!1,c("stop"),f.$emit("related"+g)}).error(function(b,c){a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RefreshHelper",["RestServices","Utilities","PaginationHelpers"]).factory("Refresh",["ProcessErrors","Rest","Wait","Empty","PageRangeSetup",function(a,b,c,d,e){return function(d){var f=d.scope,g=d.set,h=d.iterator,i=d.url;f.current_url=i,b.setUrl(i),b.get().success(function(a){var b,d;for(e({scope:f,count:a.count,next:a.next,previous:a.previous,iterator:h}),f[h+"Loading"]=!1,b=1;3>=b;b++)d=1===b?"":b,f[h+"HoldInput"+d]=!1;f[g]=a.results,window.scrollTo(0,0),c("stop"),f.$emit("PostRefresh")}).error(function(b,c){f[h+"HoldInput"]=!1,a(f,b,c,null,{hdr:"Error!",msg:"Failed to retrieve "+g+". GET returned status: "+c})})}}]),angular.module("RelatedSearchHelper",["RestServices","Utilities","RefreshRelatedHelper"]).factory("RelatedSearchInit",["$timeout","Alert","Rest","RefreshRelated","Wait",function(a,b,c,d,e){return function(a){function b(a){var b,c,d,e;for(e in h.related)if("tree"!==h.related[e].type&&(void 0===a||a===h.related[e].iterator)){b=h.related[e].iterator;for(d in h.related[e].fields)if(h.related[e].fields[d].key){f[b+"SearchField"]=d,f[b+"SearchFieldLabel"]=h.related[e].fields[d].label;break}f[b+"SortOrder"]=null,f[b+"SearchType"]="icontains",f[b+"SearchTypeLabel"]="Contains",f[b+"SearchValue"]=null,f[b+"SelectShow"]=!1,f[b+"ShowStartBtn"]=!0,f[b+"HideAllStartBtn"]=!1,c=f[b+"SearchField"],!h.related[e].fields[c].searchType||"boolean"!==h.related[e].fields[c].searchType&&"select"!==h.related[e].fields[c].searchType||(f[b+"SelectShow"]=!0,f[b+"SearchSelectOpts"]=h.fields[c].searchOptions),h.related[e].fields[c].searchType&&"gtzero"===h.related[e].fields[c].searchType&&(f[b+"InputHide"]=!0)}}var c,f=a.scope,g=a.relatedSets,h=a.form;b(),f.resetSearch=function(a){b(a),f.search(a)},f.setSearchField=function(a,b,c){var d,e;for(e in h.related)h.related[e].iterator===a&&(d=h.related[e].fields[b]);f[a+"SearchFieldLabel"]=c,f[a+"SearchField"]=b,f[a+"SearchValue"]="",f[a+"SelectShow"]=!1,f[a+"InputHide"]=!1,f[a+"ShowStartBtn"]=!0,void 0!==d.searchType&&"gtzero"===d.searchType&&(f[a+"InputHide"]=!0,f[a+"ShowStartBtn"]=!1),void 0===d.searchType||"boolean"!==d.searchType&&"select"!==d.searchType||(f[a+"SelectShow"]=!0,f[a+"SearchSelectOpts"]=d.searchOptions),void 0!==d.searchType&&"int"===d.searchType&&(f[a+"SearchType"]="int"),f.search(a)},f.setSearchType=function(a,b,c){f[a+"SearchTypeLabel"]=c,f[a+"SearchType"]=b,f.search(a)},f.startSearch=function(a,b){13===a.keyCode&&f.search(b)},f.search=function(a){e("start"),f[a+"Loading"]=!0,f[a+"HoldInput"]=!0,f[a+"SearchValue"]&&(f[a+"ShowStartBtn"]=!1),"host"===a&&"has_active_failures"===f.hostSearchField&&(f.hostFailureFilter=f.hostSearchSelectValue&&1===f.hostSearchSelectValue.value?!0:!1);var b,i,j,k,l;for(i in g)if(g[i].iterator===a){j=i,k=g[i].url;for(b in h.related[i].fields)h.related[i].fields[b].key&&(l=h.related[i].fields[b].desc?"-"+b:b);break}l=null===f[a+"SortOrder"]?l:f[a+"SortOrder"],c=h.related[j].fields[f[a+"SearchField"]],f[a+"SelectShow"]===!1&&""!==f[a+"SearchValue"]&&void 0!==f[a+"SearchValue"]||f[a+"SelectShow"]&&f[a+"SearchSelectValue"]||c.searchType&&"gtzero"===c.searchType?(f[a+"SearchParams"]=c.sourceModel?c.sourceModel+"__"+c.sourceField+"__":c.searchField?c.searchField+"__":f[a+"SearchField"]+"__",f[a+"SearchParams"]+=!c.searchType||"int"!==c.searchType&&"boolean"!==c.searchType?c.searchType&&"gtzero"===c.searchType?"gt=0":f[a+"SearchType"]+"=":"int=",!c.searchType||"boolean"!==c.searchType&&"select"!==c.searchType?(void 0===c.searchType||"gtzero"===c.searchType)&&(f[a+"SearchParams"]+=encodeURI(f[a+"SearchValue"])):f[a+"SearchParams"]+=f[a+"SearchSelectValue"].value,f[a+"SearchParams"]+=l?"&order_by="+encodeURI(l):""):f[a+"SearchParams"]=l?"order_by="+encodeURI(l):"",f[a+"Page"]=0,k+=k.match(/\/$/)?"?":"&",k+=f[a+"SearchParams"],k+=f[a+"PageSize"]?"&page_size="+f[a+"PageSize"]:"",d({scope:f,set:j,iterator:a,url:k})},f.sort=function(a,b){var c,d,e,g;$("."+a+" .list-header").each(function(){if($(this).attr("id")!==a+"-"+b+"-header"){var c=$(this).find("i");c.attr("class","icon-sort")}}),d=$("#"+a+"-"+b+"-header i"),e="",d.hasClass("icon-sort")?(d.removeClass("icon-sort"),d.addClass("icon-sort-up")):d.hasClass("icon-sort-up")?(d.removeClass("icon-sort-up"),d.addClass("icon-sort-down"),e="-"):d.hasClass("icon-sort-down")&&(d.removeClass("icon-sort-down"),d.addClass("icon-sort-up"));for(g in h.related)h.related[g].iterator===a&&(c=h.related[g].fields[b].sourceModel?e+h.related[g].fields[b].sourceModel+"__"+h.related[g].fields[b].sourceField:e+b);f[a+"SortOrder"]=c,f.search(a)}}}]),angular.module("SearchHelper",["RestServices","Utilities","RefreshHelper"]).factory("SearchInit",["Alert","Rest","Refresh","$location","GetBasePath","Empty","$timeout","Wait","Store",function(a,b,c,d,e,f,g,h,i){return function(a){function b(a){var b,c,d,e;e=void 0===a||1===a?"":a,l[p+"SearchField"+e]="",l[p+"SearchFieldLabel"+e]="";for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&o.fields[c].key){o.fields[c].sourceModel?(d=o.fields[c].sourceModel+"__"+o.fields[c].sourceField,r=o.fields[c].desc?"-"+d:d):r=o.fields[c].desc?"-"+c:c,(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)&&(l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label);break}if(f(l[p+"SearchField"+e]))for(c in o.fields)if((void 0===o.fields[c].searchWidget&&1===a||o.fields[c].searchWidget===a)&&(void 0===o.fields[c].searchable||o.fields[c].searchable===!0)){l[p+"SearchField"+e]=c,l[p+"SearchFieldLabel"+e]=o.fields[c].label;break}l[p+"SearchType"+e]="icontains",l[p+"SearchTypeLabel"+e]="Contains",l[p+"SearchParams"+e]="",l[p+"SearchValue"+e]="",l[p+"SelectShow"+e]=!1,l[p+"HideSearchType"+e]=!1,l[p+"InputDisable"+e]=!1,l[p+"ExtraParms"+e]="",l[p+"ShowStartBtn"+e]=!0,l[p+"HideAllStartBtn"+e]=!1,l[p+"SearchPlaceholder"+e]=o.fields[l[p+"SearchField"+e]]&&o.fields[l[p+"SearchField"+e]].searchPlaceholder?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[p+"SearchField"+e]].searchPlaceholder]:o.fields[l[p+"SearchField"+e]].searchPlaceholder:"Search",l[p+"InputDisable"+e]=o.fields[l[p+"SearchField"+e]]&&"all"===o.fields[l[p+"SearchField"+e]].searchObject?!0:!1,b=l[p+"SearchField"+e],o.fields[b]&&(!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType||(l[p+"SelectShow"+e]=!0,l[p+"SearchSelectOpts"+e]=o.fields[b].searchOptions),o.fields[b].searchType&&"int"===o.fields[b].searchType&&(l[p+"HideSearchType"+e]=!0),o.fields[b].searchType&&"gtzero"===o.fields[b].searchType&&(l[p+"InputHide"+e]=!0))}var e,g,j,k,l=a.scope,m=a.set,n=a.url,o=a.list,p=a.iterator?a.iterator:o.iterator,q=a.setWidgets===!1?!1:!0,r=a.sort_order||"";if(q)for(e=o.searchWidgets?o.searchWidgets:1,g=1;e>=g;g++)j=1===g?"":g,$("#search-widget-container"+j)&&b(g);k={set:m,defaultUrl:n,list:o,iterator:p,sort_order:r},i("CurrentSearchParams",k),l.setSearchField=function(a,b,c,d){var e=void 0===d||1===d?"":d;l[a+"SearchFieldLabel"+e]=c,l[a+"SearchField"+e]=b,l[a+"SearchValue"+e]="",l[a+"SelectShow"+e]=!1,l[a+"HideSearchType"+e]=!1,l[a+"InputHide"+e]=!1,l[a+"SearchType"+e]="icontains",l[a+"InputDisable"+e]="all"===o.fields[b].searchObject?!0:!1,l[a+"ShowStartBtn"+e]=!0,l[a+"SearchPlaceholder"+e]=o.fields[l[a+"SearchField"+e]]&&o.fields[l[a+"SearchField"+e]].searchPlaceholder?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]?l[o.fields[l[a+"SearchField"+e]].searchPlaceholder]:o.fields[l[a+"SearchField"+e]].searchPlaceholder:"Search",o.fields[b].searchType&&"gtzero"===o.fields[b].searchType?(l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1,l.search(a)):o.fields[b].searchSingleValue?(l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"SearchSelectValue"+e]="boolean"===o.fields[b].searchType&&"true"===o.fields[b].searchValue?{value:1}:"boolean"===o.fields[b].searchType&&"false"===o.fields[b].searchValue?{value:0}:{value:o.fields[b].searchValue},l[a+"ShowStartBtn"+e]=!1):"in"===o.fields[b].searchType?(l[a+"SearchType"+e]="in",l[a+"SearchValue"+e]=o.fields[b].searchValue,l[a+"InputDisable"+e]=!0,l[a+"ShowStartBtn"+e]=!1):!o.fields[b].searchType||"boolean"!==o.fields[b].searchType&&"select"!==o.fields[b].searchType&&"select_or"!==o.fields[b].searchType?o.fields[b].searchType&&"int"===o.fields[b].searchType?l[a+"SearchType"+e]="int":o.fields[b].searchType&&"isnull"===o.fields[b].searchType&&(l[a+"SearchType"+e]="isnull",l[a+"InputDisable"+e]=!0,l[a+"SearchValue"+e]="true",l[a+"ShowStartBtn"+e]=!1):(l[a+"SelectShow"+e]=!0,l[a+"SearchSelectOpts"+e]=o.fields[b].searchOptions),l.search(a)},l.resetSearch=function(a){var c,e=o.searchWidgets?o.searchWidgets:1;for(c=1;e>=c;c++)b(c);window.location="/#"+d.path(),l.search(a)},l.removeDoSearch&&l.removeDoSearch(),l.removeDoSearch=l.$on("doSearch",function(a,b,d,e){l[b+"Loading"]=void 0===e||e===!0?!0:!1;var f,g=n;l[b+"Page"]=d?parseInt(d)-1:0,l[b+"SearchParams"]&&(g+=/\/$/.test(g)?"?"+l[b+"SearchParams"]:"&"+l[b+"SearchParams"]),f=/\/$/.test(g)?"?":"&",g+=l[b+"_page_size"]?f+"page_size="+l[b+"_page_size"]:"",d&&(f=/\/$/.test(g)?"?":"&",g+=f+"page="+d),l[b+"ExtraParms"]&&(f=/\/$/.test(g)?"?":"&",g+=f+l[b+"ExtraParms"]),g=g.replace(/\&\&/,"&"),c({scope:l,set:m,iterator:b,url:g})}),l.removePrepareSearch&&l.removePrepareSearch(),l.removePrepareSearch=l.$on("prepareSearch",function(a,b,c,d,e){h("start"),l[b+"SearchParams"]="";var f,g,i=o.searchWidgets?o.searchWidgets:1;for(f=1;i>=f;f++)g=1===f?"":f,$("#search-widget-container"+g)&&o.fields[l[b+"SearchField"+g]]&&o.fields[l[b+"SearchField"+g]].searchObject&&("all"!==o.fields[l[b+"SearchField"+g]].searchObject?(l[b+"HideAllStartBtn"+g]=!1,l[b+"SearchValue"+g]?(l[b+"ShowStartBtn"+g]=!1,l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+g]].searchOnID?"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__id="+l[b+"SearchValue"+g]:"&"+o.fields[l[b+"SearchField"+g]].searchObject+"__name__icontains="+l[b+"SearchValue"+g]):(l[b+"ShowStartBtn"+g]=!0,l[b+"SearchParams"]+="&"+o.fields[l[b+"SearchField"+g]].searchField+"="+o.fields[l[b+"SearchField"+g]].searchObject)):l[b+"HideAllStartBtn"+g]=!0);l.$emit("prepareSearch2",b,c,d,e)}),l.removePrepareSearch2&&l.removePrepareSearch2(),l.removePrepareSearch2=l.$on("prepareSearch2",function(a,b,c,d,e){var g,h,i=o.searchWidgets?o.searchWidgets:1;for(g=1;i>=g;g++)h=1===g?"":g,l[b+"HoldInput"+h]=!0,$("#search-widget-container"+h)&&o.fields[l[b+"SearchField"+h]]&&!o.fields[l[b+"SearchField"+h]].searchObject&&(l[b+"ShowStartBtn"+h]=l[b+"SearchValue"+h]?!1:!0,(!l[b+"SelectShow"+h]&&!f(l[b+"SearchValue"+h])||l[b+"SelectShow"+h]&&l[b+"SearchSelectValue"+h]||o.fields[l[b+"SearchField"+h]]&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=o.fields[l[b+"SearchField"+h]].searchField?"&"+o.fields[l[b+"SearchField"+h]].searchField+"__":o.fields[l[b+"SearchField"+h]].sourceModel?"&"+o.fields[l[b+"SearchField"+h]].sourceModel+"__"+o.fields[l[b+"SearchField"+h]].sourceField+"__":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?"&"+l[b+"SearchField"+h]+"__":"&"+l[b+"SearchField"+h]+"__",l[b+"SearchParams"]+=!o.fields[l[b+"SearchField"+h]].searchType||"int"!==o.fields[l[b+"SearchField"+h]].searchType&&"boolean"!==o.fields[l[b+"SearchField"+h]].searchType?o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"===o.fields[l[b+"SearchField"+h]].searchType?"gt=0":"select"!==o.fields[l[b+"SearchField"+h]].searchType||""!==l[b+"SearchSelectValue"+h].value&&null!==l[b+"SearchSelectValue"+h].value?l[b+"SearchType"+h]+"=":"iexact=":"int=",!o.fields[l[b+"SearchField"+h]].searchType||"boolean"!==o.fields[l[b+"SearchField"+h]].searchType&&"select"!==o.fields[l[b+"SearchField"+h]].searchType?(!o.fields[l[b+"SearchField"+h]].searchType||o.fields[l[b+"SearchField"+h]].searchType&&"or"!==o.fields[l[b+"SearchField"+h]].searchType&&"gtzero"!==o.fields[l[b+"SearchField"+h]].searchType)&&(l[b+"SearchParams"]+=encodeURI(l[b+"SearchValue"+h])):l[b+"SearchParams"]+=l[b+"SearchSelectValue"+h].value));("inventory"===b&&l.inventoryFailureFilter||"host"===b&&l.hostFailureFilter)&&(l[b+"SearchParams"]+="&has_active_failures=true"),r&&(l[b+"SearchParams"]+=l[b+"SearchParams"]?"&":"",l[b+"SearchParams"]+="order_by="+encodeURI(r)),l.$emit("doSearch",b,c,d,e)}),l.startSearch=function(a,b){13===a.keyCode&&l.search(b)},l.search=function(a,b,c){c=void 0===c?!0:!1,c&&(l[m]=[]),l.$emit("prepareSearch",a,b,c)},l.sort=function(a){$(".list-header").each(function(){if($(this).attr("id")!==a+"-header"){var b=$(this).find("i");b.attr("class","fa fa-sort")}});var b=$("#"+a+"-header i"),c="";b.hasClass("fa-sort")?(b.removeClass("fa-sort"),b.addClass("fa-sort-up")):b.hasClass("fa-sort-up")?(b.removeClass("fa-sort-up"),b.addClass("fa-sort-down"),c="-"):b.hasClass("fa-sort-down")&&(b.removeClass("fa-sort-down"),b.addClass("fa-sort-up")),r=o.fields[a].searchField?c+o.fields[a].searchField:o.fields[a].sortField?c+o.fields[a].sortField:o.fields[a].sourceModel?c+o.fields[a].sourceModel+"__"+o.fields[a].sourceField:c+a,l.search(o.iterator)},l.searchCleanup=function(){l.removeDoSearch(),l.removePrepareSearch(),l.removePrepareSearch2()}}}]),angular.module("TeamHelper",["RestServices","Utilities","OrganizationListDefinition","SearchHelper","PaginationHelpers","ListGenerator"]).factory("SetTeamListeners",["Alert","Rest",function(a,b){return function(a){var c=a.scope,d=a.set,e=a.iterator;c.$on("TeamResultFound",function(a,b,f){var g,h,i,j;if(f.length===b.length){for(i="organization",j="organization_name",g=0;gSelect existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.",base:"users",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{},fieldActions:{}}),angular.module("CloudCredentialsListDefinition",[]).value("CloudCredentialList",{name:"cloudcredentials",iterator:"cloudcredential",selectTitle:"Add Cloud Credentials",editTitle:"Cloud Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},team:{label:"Team",ngBind:"credential.team_name",sourceModel:"team",sourceField:"name",excludeModal:!0},user:{label:"User",ngBind:"credential.user_username",sourceModel:"user",sourceField:"username",excludeModal:!0}},actions:{add:{mode:"all",ngClick:"addCredential()","class":"btn-sm",awToolTip:"Create a new credential"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash-o",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("CredentialsListDefinition",[]).value("CredentialList",{name:"credentials",iterator:"credential",selectTitle:"Add Credentials",editTitle:"Credentials",selectInstructions:"
Select existing credentials by clicking each credential or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new credential by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",excludeModal:!1},kind:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0}},actions:{add:{mode:"all",ngClick:"addCredential()",awToolTip:"Create a new credential"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{ngClick:"editCredential(credential.id)",icon:"fa-edit",label:"Edit","class":"btn-sm",awToolTip:"Edit credential",dataPlacement:"top"},"delete":{ngClick:"deleteCredential(credential.id, credential.name)",icon:"fa-trash",label:"Delete","class":"btn-sm",awToolTip:"Delete credential",dataPlacement:"top"}}}),angular.module("GroupListDefinition",[]).value("GroupList",{name:"groups",iterator:"group",selectTitle:"Copy Groups",editTitle:"Groups",index:!0,well:!1,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{help:{awPopOver:"Choose groups by clicking on each group you wish to add. Click the Select button to add the groups to the selected inventory group.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Adding Groups"}},fieldActions:{edit:{label:"Edit",ngClick:"editGroup(group.id)",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit group",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteGroup(group.id, group.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete group",dataPlacement:"top"}}}),angular.module("HomeGroupListDefinition",[]).value("HomeGroupList",{name:"home_groups",iterator:"group",editTitle:"Groups",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Group",ngClick:"editGroup(group.id, group.inventory)",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-6 ellipsis"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ /#/inventories/' + group.inventory + '/' }}"},source:{label:"Source",searchType:"select",searchOptions:[{name:"ec2",value:"ec2"},{name:"none",value:""},{name:"rax",value:"rax"}],sourceModel:"inventory_source",sourceField:"source",searchOnly:!0},has_external_source:{label:"Has external source?",searchType:"in",searchValue:"ec2,rax",searchOnly:!0,sourceModel:"inventory_source",sourceField:"source"},has_active_failures:{label:"Has failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},last_update_failed:{label:"Update failed?",searchType:"select",searchSingleValue:!0,searchValue:"failed",searchOnly:!0,sourceModel:"inventory_source",sourceField:"status"},id:{label:"ID",searchOnly:!0}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",awToolTip:"{{ group.status_tooltip }}",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",dataPlacement:"top",ngHref:"/#/inventories/{{ group.inventory }}/",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",ngShow:"(group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate(group.id)",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"(group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{label:"Edit",mode:"all",ngClick:"editGroup(group.id)",awToolTip:"Edit group",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HomeHostListDefinition",[]).value("HomeHostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,hover:!0,well:!0,fields:{name:{key:!0,label:"Name",columnClass:"col-lg-4 col-md3 col-sm-3 col-xs-7 ellipsis",ngClick:"editHost(host.id, host.name)"},inventory_name:{label:"Inventory",sourceModel:"inventory",sourceField:"name",columnClass:"col-lg-3 col-md2 col-sm-2 hidden-xs elllipsis",linkTo:"{{ '/#/inventories/' + host.inventory }}"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Has failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_inventory_sources:{label:"Has external source?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},id:{label:"ID",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{label:"Edit",ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"}},actions:{stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("HostListDefinition",[]).value("HostList",{name:"hosts",iterator:"host",selectTitle:"Add Existing Hosts",editTitle:"Hosts",index:!0,well:!1,fields:{name:{key:!0,label:"Host Name",linkTo:"/inventories/{{ inventory_id }}/hosts/{{ host.id }}"},description:{label:"Description"}},actions:{help:{awPopOver:"Select hosts by clicking on each host you wish to add. Add the selected hosts to the group by clicking the Select button.",dataContainer:"#form-modal .modal-content",mode:"all",awToolTip:"Click for help",dataTitle:"Selecting Hosts"}},fieldActions:{edit:{label:"Edit",ngClick:"editHost({{ host.id }})",icon:"icon-edit","class":"btn-xs",awToolTip:"Edit host",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash","class":"btn-xs",awToolTip:"Delete host",dataPlacement:"top"}}}),angular.module("InventoriesListDefinition",[]).value("InventoryList",{name:"inventories",iterator:"inventory",selectTitle:"Add Inventories",editTitle:"Inventories",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},organization:{label:"Organization",ngBind:"inventory.summary_fields.organization.name",linkTo:"/#/organizations/{{ inventory.organization }}",sourceModel:"organization",sourceField:"name",excludeModal:!0},has_inventory_sources:{label:"Cloud sourced?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},has_active_failures:{label:"Failed hosts?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0},inventory_sources_with_failures:{label:"Sync failures?",searchType:"gtzero",searchValue:"true",searchOnly:!0}},actions:{add:{mode:"all",ngClick:"addInventory()",awToolTip:"Create a new inventory"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{status:{ngHref:"inventory.status_link",iconClass:"{{ 'fa fa-cloud icon-cloud-' + inventory.status_class }}",awToolTip:"{{ inventory.status_tip }}",dataPlacement:"top"},failed_hosts:{ngHref:"inventory.failed_hosts_link",iconClass:"{{ 'fa icon-failures-' + inventory.failed_hosts_class }}",awToolTip:"{{ inventory.failed_hosts_tip }}",dataPlacement:"top"},edit:{label:"Edit",ngClick:"editInventoryProperties(inventory.id)",awToolTip:"Edit inventory",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteInventory(inventory.id, inventory.names')",awToolTip:"Delete inventory",dataPlacement:"top"}}}),angular.module("InventoryGroupsDefinition",[]).value("InventoryGroups",{name:"groups",iterator:"group",editTitle:"{{ inventory_name }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,filterBy:"{ show: true }","class":"table-condensed table-no-border",fields:{name:{label:"Groups",key:!0,ngClick:"showHosts(group.id,group.group_id, false)",ngClass:"group.selected_class",hasChildren:!0,columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",nosort:!0,awDroppable:"{{ group.isDroppable }}",awDraggable:"{{ group.isDraggable }}",dataContainment:"#groups_table",dataTreeId:"{{ group.id }}",dataGroupId:"{{ group.group_id }}",dataType:"group"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createGroup()",awToolTip:"Create a new group"},properties:{mode:"all",awToolTip:"Edit inventory properties",ngClick:"editInventoryProperties()"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refreshGroups()"},stream:{ngClick:"showGroupActivity()",awToolTip:"View Activity Stream",mode:"all"},help:{mode:"all",awToolTip:"Get help building your inventory",ngClick:"showGroupHelp()",id:"inventory-summary-help"}},fieldActions:{sync_status:{mode:"all",ngClick:"viewUpdateStatus(group.id, group.group_id)",ngShow:"group.id > 1",awToolTip:"{{ group.status_tooltip }}",dataTipWatch:"group.launch_tooltip",ngClass:"group.status_class",dataPlacement:"top"},failed_hosts:{mode:"all",awToolTip:"{{ group.hosts_status_tip }}",ngShow:"group.id > 1",dataPlacement:"top",ngClick:"showHosts(group.id, group.group_id, group.show_failures)",iconClass:"{{ 'fa icon-failures-' + group.hosts_status_class }}"},group_update:{mode:"all",ngClick:"updateGroup(group.id)",awToolTip:"{{ group.launch_tooltip }}",dataTipWatch:"group.launch_tooltip",ngShow:"group.id > 1 && (group.status !== 'running' && group.status !== 'pending' && group.status !== 'updating')",ngClass:"group.launch_class",dataPlacement:"top"},cancel:{mode:"all",ngClick:"cancelUpdate({{ group.id }})",awToolTip:"Cancel sync process","class":"red-txt",ngShow:"group.id > 1 && (group.status == 'running' || group.status == 'pending' || group.status == 'updating')",dataPlacement:"top"},edit:{mode:"all",ngClick:"editGroup({{ group.group_id + ',' + group.id }})",awToolTip:"Edit group",ngShow:"group.id > 1",dataPlacement:"top"},"delete":{mode:"all",ngClick:"deleteGroup({{ group.id + ',' + group.group_id }})",awToolTip:"Delete group",ngShow:"group.id != 1",dataPlacement:"top"}}}),angular.module("InventoryHostsDefinition",[]).value("InventoryHosts",{name:"hosts",iterator:"host",editTitle:"{{ selected_group }}",showTitle:!1,well:!0,index:!1,hover:!1,hasChildren:!0,"class":"table-condensed table-no-border",fields:{name:{key:!0,label:"Hosts",ngClick:"editHost(host.id)",searchPlaceholder:"search_place_holder",columnClass:"col-lg-9 col-md-9 col-sm-7 col-xs-7",dataHostId:"{{ host.id }}",dataType:"host",awDraggable:"true"},enabled:{label:"Disabled?",searchSingleValue:!0,searchType:"boolean",searchValue:"false",searchOnly:!0},has_active_failures:{label:"Failed jobs?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0}},fieldActions:{enabled_flag:{iconClass:"{{ 'fa icon-enabled-' + host.enabled }}",dataPlacement:"top",awToolTip:"{{ host.enabledToolTip }}",dataTipWatch:"host.enabledToolTip",ngClick:"toggleHostEnabled(host.id, host.has_inventory_sources)"},active_failures:{awPopOver:"{{ host.job_status_html }}",dataTitle:"{{ host.job_status_title }}",awToolTip:"{{ host.badgeToolTip }}",awTipPlacement:"top",dataPlacement:"left",iconClass:"{{ 'fa icon-failures-' + host.has_active_failures }}"},edit:{ngClick:"editHost(host.id)",icon:"icon-edit",awToolTip:"Edit host",dataPlacement:"top"},"delete":{ngClick:"deleteHost(host.id, host.name)",icon:"icon-trash",awToolTip:"Delete host",dataPlacement:"top"}},actions:{columnClass:"col-lg-3 col-md-3 col-sm-5 col-xs-5",create:{mode:"all",ngClick:"createHost()",ngHide:"selected_tree_id == 1",awToolTip:"Create a new host"},stream:{ngClick:"showHostActivity()",awToolTip:"View Activity Stream",mode:"all"}}}),angular.module("JobEventsListDefinition",[]).value("JobEventList",{name:"jobevents",iterator:"jobevent",editTitle:"Job Events",index:!1,hover:!0,hasChildren:!0,filterBy:"{ show: true }",navigationLinks:{details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",active:!0,icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",icon:"icon-laptop"}},fields:{created:{label:"Created On",columnClass:"col-lg-1 col-md-1 hidden-sm hidden-xs",key:!0,nosort:!0,searchable:!1,link:!1},status:{label:"Status",showValue:!1,columnClass:"col-sm-1 col-xs-2 text-center",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}],nosort:!0,searchable:!1,ngClick:"viewJobEvent({{ jobevent.id }})",awToolTip:"{{ jobevent.statusBadgeToolTip }}",dataPlacement:"top",badgeIcon:"fa icon-job-{{ jobevent.status }}",badgePlacement:"left",badgeToolTip:"{{ jobevent.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgClick:"viewJobEvent({{ jobevent.id }})"},event_display:{label:"Event",hasChildren:!0,ngClick:"toggleChildren(jobevent.id, jobevent.related.children)",nosort:!0,searchable:!1,ngClass:"{{ jobevent.class }}",appendHTML:"jobevent.event_detail"},host:{label:"Host",ngBind:"jobevent.summary_fields.host.name",ngHref:"{{ jobevent.hostLink }}",searchField:"hosts__name",nosort:!0,searchOnly:!1,id:"job-event-host-header","class":"break",columnClass:"col-lg-2 hidden-sm hidden-xs"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{columnClass:"col-sm-1 col-xs-2",view:{label:"View",ngClick:"viewJobEvent(jobevent.id)",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("JobHostDefinition",[]).value("JobHostList",{name:"jobhosts",iterator:"jobhost",editTitle:"All summaries",index:!0,hover:!0,navigationLinks:{ngHide:"host_id !== null",details:{href:"/#/jobs/{{ job_id }}",label:"Status",icon:"icon-zoom-in",ngShow:"job_id !== null"},events:{href:"/#/jobs/{{ job_id }}/job_events",label:"Events",icon:"icon-list-ul"},hosts:{href:"/#/jobs/{{ job_id }}/job_host_summaries",label:"Host Summary",active:!0,icon:"icon-laptop"}},fields:{job:{label:"Job ID",ngClick:"showJob(jobhost.job)",columnShow:"host_id !== null",key:!0,desc:!0},host:{label:"Host",key:!0,sourceModel:"host",sourceField:"name",ngBind:"jobhost.host_name",ngHref:"jobhost.hostLinkTo"},status:{label:"Status",badgeNgHref:"{{ jobhost.statusLinkTo }}",badgeIcon:"fa icon-job-{{ jobhost.status }}",badgePlacement:"left",badgeToolTip:"{{ jobhost.statusBadgeToolTip }}",badgeTipPlacement:"top",ngHref:"{{ jobhost.statusLinkTo }}",awToolTip:"{{ jobhost.statusBadgeToolTip }}",dataPlacement:"top",searchField:"failed",searchType:"boolean",searchOptions:[{name:"success",value:0},{name:"error",value:1}]},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},ok:{label:"Success",searchable:!1},changed:{label:"Changed",searchable:!1},failures:{label:"Failure",searchable:!0,searchLabel:"Contains failed events?",searchType:"gtzero"},dark:{label:"Unreachable",searchable:!0,searchType:"gtzero",searchLabel:"Contains unreachable hosts?"},skipped:{label:"Skipped",searchable:!1}},actions:{help:{awPopOver:"
\n
Success
Tasks successfully executed on the host.
\n
Changed
Actions taken on the host.
\n
Failure
Tasks that failed on the host.
\n
Unreachable
Times the ansible server could not reach the host.
\n
Skipped
Tasks bypassed and not performed on the host due to prior task failure or the host being unreachable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Job Host Summary",id:"jobhost-help-button"},refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refresh()",ngShow:"host_id == null"}},fieldActions:{}}),angular.module("JobTemplatesListDefinition",[]).value("JobTemplateList",{name:"job_templates",iterator:"job_template",selectTitle:"Add Job Template",editTitle:"Job Templates",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addJobTemplate()",basePaths:["job_templates"],awToolTip:"Create a new template"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",icon:"icon-comments-alt",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editJobTemplate(job_template.id)",icon:"icon-edit",awToolTip:"Edit template","class":"btn-default btn-xs",dataPlacement:"top"},submit:{label:"Launch",icon:"icon-rocket",mode:"all","class":"btn-xs btn-success",ngClick:"submitJob(job_template.id)",awToolTip:"Start a job using this template",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteJobTemplate(job_template.id, job_template.name)",icon:"icon-trash","class":"btn-danger btn-xs",awToolTip:"Delete template",dataPlacement:"top"}}}),angular.module("JobsListDefinition",[]).value("JobList",{name:"jobs",iterator:"job",editTitle:"Jobs",index:!1,hover:!0,"class":"jobs-table",fields:{id:{label:"Job ID",key:!0,desc:!0,searchType:"int"},inventory:{label:"Inventory ID",searchType:"int",searchOnly:!0},created:{label:"Create On",link:!1,searchable:!1},job_template:{label:"Job Template",ngBind:"job.summary_fields.job_template.name",ngHref:"{{ '/#/job_templates/' + job.job_template }}",sourceModel:"job_template",sourceField:"name"},failed:{label:"Job failed?",searchSingleValue:!0,searchType:"boolean",searchValue:"true",searchOnly:!0,nosort:!0},status:{label:"Status","class":"job-{{ job.status }}",searchType:"select",linkTo:"{{ job.statusLinkTo }}",searchOptions:[{name:"new",value:"new"},{name:"waiting",value:"waiting"},{name:"pending",value:"pending"},{name:"running",value:"running"},{name:"successful",value:"successful"},{name:"error",value:"error"},{name:"failed",value:"failed"},{name:"canceled",value:"canceled"}],badgeIcon:"fa icon-job-{{ job.status }}",badgePlacement:"left",badgeToolTip:"{{ job.statusBadgeToolTip }}",badgeTipPlacement:"top",badgeNgHref:"{{ job.statusLinkTo }}",awToolTip:"{{ job.statusBadgeToolTip }}",dataPlacement:"top"}},actions:{refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"}},fieldActions:{submit:{label:"Relaunch",icon:"icon-rocket",mode:"all",ngClick:"submitJob(job.id, job.summary_fields.job_template.name)",awToolTip:"Start the job",dataPlacement:"top"},cancel:{label:"Stop",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Cancel a running or pending job",ngShow:"job.status == 'pending' || job.status == 'running' || job.status == 'waiting'",dataPlacement:"top"},"delete":{label:"Delete",mode:"all",ngClick:"deleteJob(job.id)",awToolTip:"Delete the job",ngShow:"job.status != 'pending' && job.status != 'running' && job.status != 'waiting'",dataPlacement:"top"},dropdown:{type:"DropDown",label:"View",icon:"fa-search-plus","class":"btn-default btn-xs",options:[{ngClick:"editJob(job.id, job.summary_fields.job_template.name)",label:"Status"},{ngClick:"viewEvents(job.id, job.summary_fields.job_template.name)",label:"Events",ngHide:"job.status == 'new'"},{ngClick:"viewSummary(job.id, job.summary_fields.job_template.name)",label:"Host Summary",ngHide:"job.status == 'new'"}]}}}),angular.module("OrganizationListDefinition",[]).value("OrganizationList",{name:"organizations",iterator:"organization",selectTitle:"Add Organizations",editTitle:"Organizations",hover:!0,index:!1,fields:{name:{key:!0,label:"Name"},description:{label:"Description"}},actions:{add:{mode:"all",ngClick:"addOrganization()",awToolTip:"Create a new organization"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{}}),angular.module("PermissionListDefinition",[]).value("PermissionList",{name:"permissions",iterator:"permission",selectTitle:"Add Permission",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',editTitle:"Permissions",index:!0,well:!0,fields:{name:{key:!0,label:"Name",ngClick:"editPermission(permission.id)"},inventory:{label:"Inventory",sourceModel:"inventory",sourceField:"name",ngBind:"permission.summary_fields.inventory.name"},project:{label:"Project",sourceModel:"project",sourceField:"name",ngBind:"permission.summary_fields.project.name"},permission_type:{label:"Permission"}},actions:{add:{mode:"all",ngClick:"addPermission()",awToolTip:"Add a new permission",ngShow:"PermissionAddAllowed"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editPermission(permission.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit permission",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deletePermission(permission.id, permission.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete permission",ngShow:"PermissionAddAllowed",dataPlacement:"top"}}}),angular.module("ProjectsListDefinition",[]).value("ProjectList",{name:"projects",iterator:"project",selectTitle:"Add Project",editTitle:"Projects",selectInstructions:"
Select existing projects by clicking each project or checking the related checkbox. When finished, click the blue Select button, located bottom right.
Create a brand new project by clicking the green Create New button.
",index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description",columnClass:"hidden-sm hidden-xs",excludeModal:!0},scm_type:{label:"Type",searchType:"select",searchOptions:[],excludeModal:!0,nosort:!0},status:{label:"Status",ngClick:"showSCMStatus(project.id)",awToolTip:"View details of last SCM Update",dataPlacement:"top",badgeIcon:"{{ 'fa icon-failures-' + project.badge }}",badgePlacement:"left",searchType:"select",searchOptions:[],excludeModal:!0},last_updated:{label:"Last Updated",type:"date",excludeModal:!0,searchable:!1}},actions:{add:{mode:"all",ngClick:"addProject()",awToolTip:"Create a new project"},help:{awPopOver:"
\n
Updating
A source control update is in progress.
\n
Never Updated
This project has not yet been updated from source control.
\n
Failed
An error occurred during the most recent source control update, click the status text for more information.
\n
Successful
TThe latest source control update completed successfully.
\n
Missing
The previously configured local project directory is missing.
\n
N/A
The project is not linked to source control, so updates are not applicable.
\n
\n",dataPlacement:"left",dataContainer:"body",mode:"all",awToolTip:"Click for help",awTipPlacement:"top"},refresh:{mode:"all",awToolTip:"Refresh the page",ngClick:"refresh()"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editProject(project.id)",awToolTip:"Edit project properties",dataPlacement:"top"},scm_update:{label:"Update",ngClick:"SCMUpdate(project.id)",awToolTip:"{{ project.scm_update_tooltip }}",ngClass:"project.scm_type_class",dataPlacement:"top"},cancel:{label:"Stop",ngClick:"cancelUpdate(project.id, project.name)",awToolTip:"Cancel a running SCM update process",ngShow:"project.status == 'updating'",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteProject(project.id, project.name)",awToolTip:"Permanently remove project from the database",ngShow:"project.status !== 'updating'",dataPlacement:"top"}}}),angular.module("StreamListDefinition",[]).value("StreamList",{name:"activities",iterator:"activity",editTitle:"Activity Stream",selectInstructions:"",index:!1,hover:!0,"class":"table-condensed",searchWidgets:3,fields:{timestamp:{label:"Event Time",key:!0,desc:!0,noLink:!0,searchable:!1},user:{label:"Initiated by",ngBindHtml:"activity.user",sourceModel:"actor",sourceField:"username",searchPlaceholder:"Username",searchWidget:1},description:{label:"Action",ngBindHtml:"activity.description",nosort:!0,searchable:!1,columnClass:"col-lg-7"},system_event:{label:"System event",searchOnly:!0,searchType:"isnull",sourceModel:"actor",sourceField:"username",searchWidget:1},all_objects:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All resources",searchWidget:2},credential_search:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Credential name",searchWidget:2,searchField:"object1"},group_search:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Group name",searchWidget:2,searchField:"object1"},host_search:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Host name",searchWidget:2,searchField:"object1"},inventory_search:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Inventory name",searchWidget:2,searchField:"object1"},job_template_search:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Job template name",searchWidget:2,searchField:"object1"},job_search:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:2,searchField:"object1"},organization_search:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Organization name",searchWidget:2,searchField:"object1"},project_search:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Project name",searchWidget:2,searchField:"object1"},user_search:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Primary username",searchWidget:2,searchField:"object1"},all_objects3:{label:"All",searchOnly:!0,searchObject:"all",searchPlaceholder:"All related resources",searchWidget:3,searchField:"object2"},credential_search3:{label:"Credential",searchOnly:!0,searchObject:"credential",searchPlaceholder:"Related credential name",searchWidget:3,searchField:"object2"},group_search3:{label:"Group",searchOnly:!0,searchObject:"group",searchPlaceholder:"Related group name",searchWidget:3,searchField:"object2"},host_search3:{label:"Host",searchOnly:!0,searchObject:"host",searchPlaceholder:"Related host name",searchWidget:3,searchField:"object2"},inventory_search3:{label:"Inventory",searchOnly:!0,searchObject:"inventory",searchPlaceholder:"Related inventory name",searchWidget:3,searchField:"object2"},job_search3:{label:"Job",searchOnly:!0,searchObject:"job",searchPlaceholder:"Job id",searchOnID:!0,searchWidget:3,searchField:"object2"},job_template_search3:{label:"Job Template",searchOnly:!0,searchObject:"job_template",searchPlaceholder:"Related job template name",searchWidget:3,searchField:"object2"},organization_search3:{label:"Organization",searchOnly:!0,searchObject:"organization",searchPlaceholder:"Related organization name",searchWidget:3,searchField:"object2"},project_search3:{label:"Project",searchOnly:!0,searchObject:"project",searchPlaceholder:"Related project name",searchWidget:3,searchField:"object2"},user_search3:{label:"User",searchOnly:!0,searchObject:"user",searchPlaceholder:"Related username",searchWidget:3,searchField:"object2"}},actions:{refresh:{mode:"all","class":"btn-xs",awToolTip:"Refresh the page",ngClick:"refreshStream()"},close:{mode:"all",awToolTip:"Close Activity Stream view",ngClick:"closeStream()"}},fieldActions:{view:{label:"View",ngClick:"showDetail(activity.id)",icon:"fa-zoom-in","class":"btn-default btn-xs",awToolTip:"View event details",dataPlacement:"top"}}}),angular.module("TeamsListDefinition",[]).value("TeamList",{name:"teams",iterator:"team",selectTitle:"Add Team",editTitle:"Teams",selectInstructions:'Click on a row to select it, and click Finished when done. Use the green button to create a new row.',index:!0,hover:!0,fields:{name:{key:!0,label:"Name"},description:{label:"Description"},organization:{label:"Organization",ngBind:"team.organization_name",sourceModel:"organization",sourceField:"name"}},actions:{add:{mode:"all",ngClick:"addTeam()",awToolTip:"Create a new team"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editTeam(team.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit team",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteTeam(team.id, team.name)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete team",dataPlacement:"top"}}}),angular.module("UserListDefinition",[]).value("UserList",{name:"users",iterator:"user",selectTitle:"Add Users",editTitle:"Users",selectInstructions:"
Select existing users by clicking each user or checking the related checkbox. When finished, click the blue Select button, located bottom right.
When available, a brand new user can be created by clicking the green Create New button.
",index:!0,hover:!0,fields:{username:{key:!0,label:"Username"},first_name:{label:"First Name"},last_name:{label:"Last Name"}},actions:{add:{label:"Create New",mode:"all",ngClick:"addUser()",basePaths:["organizations","users"],"class":"btn-xs",awToolTip:"Create a new user"},stream:{ngClick:"showActivity()",awToolTip:"View Activity Stream",mode:"all"}},fieldActions:{edit:{label:"Edit",ngClick:"editUser(user.id)",icon:"icon-edit","class":"btn-xs btn-default",awToolTip:"Edit user",dataPlacement:"top"},"delete":{label:"Delete",ngClick:"deleteUser(user.id, user.username)",icon:"icon-trash","class":"btn-xs btn-danger",awToolTip:"Delete user",dataPlacement:"top"}}}),angular.module("InventorySyncStatusWidget",["RestServices","Utilities"]).factory("InventorySyncStatus",["$rootScope","$compile",function(a,b){return function(a){function c(a){var b=a.label,c=a.count,d=a.fail,e=a.link,f=a.fail_link,g="
\n",d+="\n",d+="\n",d+=c({label:"Inventories",count:k.inventories&&k.inventories.total_with_inventory_source?k.inventories.total_with_inventory_source:0,fail:k.inventories&&k.inventories.inventory_failed?k.inventories.inventory_failed:0,link:"/#/inventories/?has_inventory_sources=true",fail_link:"/#/inventories/?inventory_sources_with_failures=true"}),e=0,f=0,k.inventory_sources)for(h in k.inventory_sources)e+=k.inventory_sources[h].total?k.inventory_sources[h].total:0,f+=k.inventory_sources[h].failed?k.inventory_sources[h].failed:0;d+=c({label:"Groups",count:e,fail:f,link:"/#/home/groups/?has_external_source=true",fail_link:"/#/home/groups/?status=failed"});for(h in k.inventory_sources)k.inventory_sources[h].total&&(d+=c({label:k.inventory_sources[h].label,count:k.inventory_sources[h].total?k.inventory_sources[h].total:0,fail:k.inventory_sources[h].failed?k.inventory_sources[h].failed:0,link:"/#/home/groups/?source="+h,fail_link:"/#/home/groups/?status=failed&source="+h}));d+="\n",d+="
\n",e+="\n",e+="\n",f=0,l.scm_types)for(h in l.scm_types)f+=l.scm_types[h].total?l.scm_types[h].total:0;e+=c({label:"Projects",link:"/#/projects",count:f,fail:l.projects&&l.projects.failed?l.projects.failed:0,fail_link:"/#/projects/?status=failed"}),i=[];for(h in l.scm_types)i.push(h);for(i.sort(),d=0;d\n",e+="
\n",e+="
\n",e+="
\n",e+="\n",g=angular.element(document.getElementById(k)),g.html(e),b(g)(j),j.$emit("WidgetLoaded")}}]),angular.module("StreamWidget",["RestServices","Utilities","StreamListDefinition","SearchHelper","PaginationHelpers","RefreshHelper","ListGenerator","StreamWidget","AuthService"]).factory("setStreamHeight",[function(){return function(){var a=$("#stream-content").height(),b=parseInt($("#tab-content-container").css("min-height").replace(/px/,"")),c=a>b?a:b;$("#tab-content-container").css({"min-height":c})}}]).factory("ShowStream",["setStreamHeight","Authorization",function(a){return function(){var b=$("#stream-container");b.css({position:"absolute",top:0,left:0,width:"100%","min-height":"100%","background-color":"#FFF"}),a(),b.show("slide",{direction:"left"},{duration:500,queue:!1})}}]).factory("HideStream",["LoadBreadCrumbs",function(a){return function(){var b=$("#stream-container");b.hide("slide",{direction:"left"},{duration:500,queue:!1}),setTimeout(function(){b.detach(),b.empty(),b.unbind(),$("#tab-content-container").css({"min-height":0})},500),a()}}]).factory("StreamBreadCrumbs",["$rootScope","$location",function(a,b){return function(){a.breadcrumbs=[];var c,d,e,f,g=b.path().split("/");for(g.splice(0,1),e=0;e=f;f++)c+="/"+g[f];for(f=0;f0)for(f=0;e>=f;f++)c+="/"+g[f];else c="/"+g[e];d=g[e],d=d.charAt(0).toUpperCase()+d.slice(1)}a.breadcrumbs.push({path:c,title:d})}}}]).factory("FixUrl",[function(){return function(a){return a.replace(/\/api\/v1\//,"/#/")}}]).factory("BuildUrl",[function(){return function(a){var b="/#/";switch(a.base){case"group":case"host":b+="home/"+a.base+"s/?id="+a.id;break;case"inventory":b+="inventories/"+a.id+"/";break;default:b+=a.base+"s/"+a.id+"/"}return b}}]).factory("BuildDescription",["FixUrl","BuildUrl",function(a,b){return function(a){function c(a){return a.replace(/^_deleted_\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d+\+\d+:\d+_/,"")}var d,e,f,g,h,i,j,k;d=a.operation,d+=/e$/.test(a.operation)?"d ":"ed ",e=d,f=a.object1,g=a.object2,h=a.summary_fields[f]?a.summary_fields[f][0]:null,i=f===g?a.summary_fields[f][1]:a.summary_fields[g]?a.summary_fields[g][0]:null,("user"===f||"user"===g)&&(a.summary_fields.user[0].name=a.summary_fields.user[0].username),i&&i.name&&!/^_delete/.test(i.name)?(i.base=g,d+=g+' '+i.name+""+("disassociate"===a.operation?" from ":" to "),e+=g+" "+i.name+("disassociate"===a.operation?" from ":" to ")):g&&(j="",i&&i.name&&(j=" "+c(i.name)),d+=g+j+("disassociate"===a.operation?" from ":" to "),e+=g+j+("disassociate"===a.operation?" from ":" to ")),h&&h.name&&!/^\_delete/.test(h.name)?(h.base=f,d+=f+' '+h.name+"",e+=f+" "+h.name):f&&(j="",k="",!h||!h.name||h&&h.name&&/^_delete/.test(h.name)?a.changes&&a.changes.name?"string"==typeof a.changes.name?(j=" "+a.changes.name,k=j):"object"==typeof a.changes.name&&Array.isArray(a.changes.name)&&(j=" "+a.changes.name[0],k=j):"job"===f&&h&&a.changes&&a.changes.job_template?"delete"!==a.operation?(h.base=f,j=' '+h.id+" "+a.changes.job_template+"",k=" "+h.id+" "+a.changes.job_template):(j=" "+h.id+" "+a.changes.job_template,k=j):"job"===f&&h&&("delete"!==a.operation?(h.base=f,j=' '+h.id+"",k=" "+h.id):(j=" "+h.id,k=j)):h&&h.name&&(j=" "+c(h.name),k=j),d+=f+j,e+=f+k),a.description=d,a.description_nolink=e}}]).factory("ShowDetail",["$rootScope","Rest","Alert","GenerateForm","ProcessErrors","GetBasePath","FormatDate","ActivityDetailForm","Empty","Find",function(a,b,c,d,e,f,g,h,i,j){return function(a){var b,c,e,f=a.activity_id,i=a.scope,k=d,l=h,m=j({list:i.activities,key:"id",val:f});m&&(m.changes_stringified=JSON.stringify(m.changes,null," "),b=m.changes_stringified.match(/\n/g),c=b?b.length:1,c=1>c?3:10,l.fields.changes.rows=10,e=k.inject(l,{mode:"edit",modal:!0,related:!1}),e.changes=m.changes_stringified,e.user=(m.summary_fields.actor?m.summary_fields.actor.username:"system")+" on "+g(new Date(m.timestamps)),e.operation=m.description_nolink,e.formModalAction=function(){$("#form-modal").modal("hide")},$("#form-modal").on("show.bs.modal",function(){$("#form-modal-body").css({width:"auto",height:"auto","max-height":"100%"})}),e.formModalActionLabel="OK",e.formModalCancelShow=!1,e.formModalInfo=!1,e.formModalHeader="Event "+m.id,e.$$phase||e.$digest())}}]).factory("Stream",["$rootScope","$location","Rest","GetBasePath","ProcessErrors","Wait","StreamList","SearchInit","PaginateInit","GenerateList","FormatDate","ShowStream","HideStream","BuildDescription","FixUrl","BuildUrl","ShowDetail","StreamBreadCrumbs","setStreamHeight","Find","Store",function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){return function(c){var e,f,o,v,w=g,x=d("activity_stream"),y=j,z=b.path().replace(/^\//,"").split("/")[0],A=c.scope,B=u("CurrentSearchParams"),C=c&&c.inventory_name?c.inventory_name:null,D=c&&c.url?c.url:null;a.flashMessage=null,D?x=D:"/home"!==b.path()&&(e="inventories"===z?"inventory":z.replace(/s$/,""),f=b.path().split("/"),f.splice(0,1),f.length>1&&/^\d+/.test(f[f.length-1])?(e=f[f.length-2],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?"+e+"__id="+f[f.length-1]):f.length>1?(e=f[f.length-1],e="inventories"===e?"inventory":e.replace(/s$/,""),x+="?or__object1="+e+"&or__object2="+e):x+="?or__object1="+e+"&or__object2="+e),$("#tab-content-container").append('
'),r(),C&&(o=t({list:a.breadcrumbs,key:"title",val:"{{ inventory_name }}"}),o&&(o.title=C)),l(),v=y.inject(w,{mode:"edit",id:"stream-content",searchSize:"col-lg-3",secondWidget:!0,activityStream:!0}),v.streamTitle=c&&c.title?c.title:null,v.closeStream=function(a){m(),v.searchCleanup&&v.searchCleanup(),B&&h({scope:A,set:B.set,list:B.list,url:B.defaultUrl,iterator:B.iterator,sort_order:B.sort_order,setWidgets:!1}),a&&b.path(a)},v.refreshStream=function(){v.search(w.iterator)},v.showDetail=function(a){q({scope:v,activity_id:a})},v.removeStreamPostRefresh&&v.removeStreamPostRefresh(),v.removeStreamPostRefresh=v.$on("PostRefresh",function(){var a,b,c,d,e,f;for(a=0;a'+v.activities[a].summary_fields.actor.username+"":"system",d=/^\_delete/,e=v.activities[a].object1,f=v.activities[a].object2,e&&v.activities[a].summary_fields[e]&&v.activities[a].summary_fields[e].name?d.test(v.activities[a].summary_fields[e].name)?v.activities[a].objects=v.activities[a].summary_fields[e].name:(c=p(v.activities[a].summary_fields.object1),v.activities[a].objects=''+v.activities[a].summary_fields[e].name+""):v.activities[a].object1&&(v.activities[a].objects=v.activities[a].object1),f&&v.activities[a].summary_fields[f]&&v.activities[a].summary_fields[f].name?d.test(v.activities[a].summary_fields.object2.name)?v.activities[a].objects+=","+v.activities[a].summary_fields[f].name:(c=p(v.activities[a].summary_fields.object2),v.activities[a].objects+=', '+v.activities[a].summary_fields[f].name+""):v.activities[a].object2&&(v.activities[a].objects+=", "+v.activities[a].object2),n(v.activities[a]);setTimeout(function(){s()},500)}),h({scope:v,set:w.name,list:w,url:x}),i({scope:v,list:w,url:x}),v.search(w.iterator)}}]),angular.module("AuthService",["ngCookies","Utilities"]).factory("Authorization",["$http","$rootScope","$location","$cookieStore","GetBasePath",function(a,b,c,d,e){return{setToken:function(a,c){d.remove("token"),d.remove("token_expires"),d.remove("userLoggedIn"),d.put("token",a),d.put("token_expires",c),d.put("userLoggedIn",!0),d.put("sessionExpired",!1),b.token=a,b.userLoggedIn=!0,b.token_expires=c,b.sessionExpired=!1},isUserLoggedIn:function(){return void 0===b.userLoggedIn&&(b.userLoggedIn=d.get("userLoggedIn"),b.sessionExpired=d.get("sessionExpired")),b.userLoggedIn},getToken:function(){return b.token?b.token:d.get("token")},retrieveToken:function(b,c){return a({method:"POST",url:e("authtoken"),data:{username:b,password:c}})},logout:function(){var a=angular.element(document.getElementById("main-view")).scope();a.$destroy(),b.$destroy(),d.remove("accordions"),d.remove("token"),d.remove("token_expires"),d.remove("current_user"),d.remove("lastPath"),d.put("userLoggedIn",!1),d.put("sessionExpired",!1),d.remove("lastPath","/home"),b.current_user={},b.license_tested=void 0,b.userLoggedIn=!1,b.sessionExpired=!1,b.token=null,b.token_expires=null,b.lastPath="/home"},getLicense:function(){return a({method:"GET",url:e("config"),headers:{Authorization:"Token "+this.getToken()}})},setLicense:function(a){a.tested=!1,d.put("license",a)},licenseTested:function(){var a,c;return void 0!==b.license_tested?c=b.license_tested:(a=d.get("license"),c=a&&void 0!==a.tested?a.tested:!1),c},getUser:function(){return a({method:"GET",url:"/api/v1/me/",headers:{Authorization:"Token "+this.getToken()}})},setUserInfo:function(a){b.current_user=a.results[0],d.put("current_user",a.results[0])},restoreUserInfo:function(){b.current_user=d.get("current_user")},getUserInfo:function(a){var c;return b.current_user?b.current_user[a]:(this.restoreUserInfo(),c=d.get("current_user"),c[a])}}}]),angular.module("InventoryTree",["Utilities","RestServices","GroupsHelper","PromptDialog"]).factory("SortNodes",[function(){return function(a){var b,c,d=[],e=[];for(b=0;b0?!0:!1,has_inventory_sources:s[e].has_inventory_sources,id:r,source:s[e].summary_fields.inventory_source.source,group_id:s[e].id,event_level:c,children:i,ngicon:s[e].children.length>0?"fa fa-minus-square-o node-toggle":"fa fa-square-o node-no-toggle",ngclick:"toggle("+r+")",related:{children:s[e].children.length>0?s[e].related.children:"",inventory_source:s[e].related.inventory_source},status:s[e].summary_fields.inventory_source.status,status_class:k["class"],status_tooltip:k.tooltip,launch_tooltip:k.launch_tip,launch_class:k.launch_class,hosts_status_tip:n.tooltip,show_failures:n.failures,hosts_status_class:n["class"],selected_class:"",show:!0,isDraggable:!0,isDroppable:!0},q.push(o),p&&o.group_id===p&&(m.selected_tree_id=r,m.selected_group_id=o.group_id),s[e].children.length>0&&j(s[e].children,r,c+1)}}function k(){e("start"),a.setUrl(b("inventory")+l+"/"),a.get().success(function(a){m.$emit("buildAllGroups",a.name,a.related.tree,a.related.groups)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory: "+l+". GET returned: "+b})})}var l=h.inventory_id,m=h.scope,n=h.refresh,o=h.emit,p=h.new_group_id,q=[],r=1;m.buildAllGroupsRemove&&m.buildAllGroupsRemove(),m.buildAllGroupsRemove=m.$on("buildAllGroups",function(b,d,f){a.setUrl(f),a.get().success(function(a){i(a),j(a,0,0),m.autoShowGroupHelp=0===a.length?!0:!1,n?(m.groups=q,m.$emit("GroupTreeRefreshed",d,q,o)):m.$emit("GroupTreeLoaded",d,q,o)}).error(function(a,b){e("stop"),c(m,a,b,null,{hdr:"Error!",msg:"Failed to get inventory tree for: "+l+". GET returned: "+b})})}),k()}}]).factory("UpdateGroup",["ApplyEllipsis","GetSyncStatusMsg","Empty",function(a,b,c){return function(d){var e,f,g,h,i,j=d.scope,k=d.group_id,l=d.properties;for(e=0;e\n',m+='
\n',m+='
\n',m+='
\n',m+='\n',m+=1===k.id||0===l.parent?"
Move Group
\n":"
Copy or Move?
\n",m+="
\n",m+='
\n',1===k.id?m+="
Are you sure you want to move group "+l.name+" to the top level?
":0===l.parent?m+="
Are you sure you want to move group "+l.name+" from the top level and make it a child of "+k.name+"?
":(m+='
\n',m+="
Would you like to copy or move group "+l.name+" to group "+k.name+"?
\n",m+="\n",i=angular.element(document.getElementById("inventory-modal-container")),i.empty().append(m),a(i)(j),$("#copy-prompt-modal").modal({backdrop:"static",keyboard:!0,show:!0}),j.moveGroup=function(){var a,b,i;$("#copy-prompt-modal").modal("hide"),e("start"),j.removeGroupRemove&&j.removeGroupRemove(),j.removeGroupRemove=j.$on("removeGroup",function(){l.parent>0?(i=d({list:j.groups,key:"id",val:l.parent}),a=h("base")+"groups/"+i.group_id+"/children/",f.setUrl(a),f.post({id:l.group_id,disassociate:1}).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to remove "+l.name+" from "+i.name+". POST returned status: "+b})})):j.$emit("GroupDeleteCompleted")}),a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id},f.setUrl(a),f.post(b).success(function(){j.$emit("removeGroup")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})},j.copyGroup=function(){$("#copy-prompt-modal").modal("hide"),e("start");var a=g(k.group_id)?h("inventory")+j.inventory_id+"/groups/":h("base")+"groups/"+k.group_id+"/children/",b={id:l.group_id,name:l.name,description:l.description,inventory:j.inventory_id};f.setUrl(a),f.post(b).success(function(){j.$emit("GroupDeleteCompleted")}).error(function(a,b){var d=g(k.group_id)?"inventory":k.name;e("stop"),c(j,a,b,null,{hdr:"Error!",msg:"Failed to add "+l.name+" to "+d+". POST returned status: "+b})})}}}]).factory("CopyMoveHost",["$compile","Alert","ProcessErrors","Find","Wait","Rest","Empty","GetBasePath",function(a,b,c,d,e,f,g,h){return function(b){var g,i,j=b.scope,k=d({list:j.groups,key:"id",val:b.target_tree_id}),l=d({list:j.hosts,key:"id",val:b.host_id}),m=!1,n="";if(l.summary_fields.all_groups)for(i=0;i\n',n+='
URL must begin with ssh, http or https and may not contain '@'
\n"),p+='\n',b.chkPass&&(p+='
Password must be stronger
\n',p+='
\n',p+='
\n',p+='\n',p+="
\n",p+=k({hdr:"Password Complexity",content:'
A password with reasonable strength is required. As you type the password a progress bar will measure the strength. Sufficient strength is reached when the bar turns green.
Password strength is judged using the following:
Minimum 8 characters in length
\n
Contains a sufficient combination of the following items:\n
\n';for(b in this.form.actions)("all"===this.form.actions[b].mode||this.form.actions[b].mode===a.mode)&&(c+=this.button({btn:this.form.actions[b],action:b,toolbar:!0}));return c+="
\n");for(d in this.form.buttons)"object"==typeof this.form.buttons[d]&&(e=this.form.buttons[d],"save"===d&&(e.label="Save",e["class"]="btn-success"),"reset"===d&&(e.label="Reset",e["class"]="btn-default"),p+='\n");p+="
\n"),k=1,l=n.related[h].base?n.related[h].base:h,l=l.replace(/^\//,"");for(g in n.related[h].fields)k++,b+=i({list:n.related[h],fld:g,options:a,base:l});b+='
\n';for(b in f.fields)void 0!==f.fields[b].searchable&&f.fields[b].searchable!==!0||(void 0!==f.fields[b].searchWidget&&1!==f.fields[b].searchWidget||1!==c)&&f.fields[b].searchWidget!==c||(h+='
\n';
+for(j in t.actions)("all"===t.actions[j].mode||t.actions[j].mode===b.mode)&&(void 0===t.actions[j].basePaths||t.actions[j].basePaths&&t.actions[j].basePaths.indexOf(c)>-1)&&(s+=this.button({btn:t.actions[j],action:j,toolbar:!0}));"select"===b.mode&&t.selectInstructions&&(k={awPopOver:t.selectInstructions,dataPlacement:"top",dataContainer:"body","class":"btn-xs btn-help",awToolTip:"Click for help",dataTitle:"Help",iconSize:"fa-lg"},s+=this.button({btn:k,action:"help",toolbar:!0})),s+="
\n');for(n in t.fields)void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+='
\n"),o=2,c=t.base?t.base:t.name,c=c.replace(/^\//,"");for(n in t.fields)o++,void 0!==t.fields[n].searchOnly&&t.fields[n].searchOnly!==!1||"lookup"===b.mode&&void 0!==t.fields[n].excludeModal&&t.fields[n].excludeModal===!0||(s+=h({list:t,fld:n,options:b,base:c}));if("select"===b.mode||"lookup"===b.mode)s+='
- *
- * @param {Object|Array} obj Object to iterate over.
- * @param {Function} iterator Iterator function.
- * @param {Object=} context Object to become context (`this`) for the iterator function.
- * @returns {Object|Array} Reference to `obj`.
- */
-function forEach(obj, iterator, context) {
- var key;
- if (obj) {
- if (isFunction(obj)){
- for (key in obj) {
- // Need to check if hasOwnProperty exists,
- // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
- if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
- iterator.call(context, obj[key], key);
- }
- }
- } else if (obj.forEach && obj.forEach !== forEach) {
- obj.forEach(iterator, context);
- } else if (isArrayLike(obj)) {
- for (key = 0; key < obj.length; key++)
- iterator.call(context, obj[key], key);
- } else {
- for (key in obj) {
- if (obj.hasOwnProperty(key)) {
- iterator.call(context, obj[key], key);
- }
- }
- }
- }
- return obj;
-}
-
-function sortedKeys(obj) {
- var keys = [];
- for (var key in obj) {
- if (obj.hasOwnProperty(key)) {
- keys.push(key);
- }
- }
- return keys.sort();
-}
-
-function forEachSorted(obj, iterator, context) {
- var keys = sortedKeys(obj);
- for ( var i = 0; i < keys.length; i++) {
- iterator.call(context, obj[keys[i]], keys[i]);
- }
- return keys;
-}
-
-
-/**
- * when using forEach the params are value, key, but it is often useful to have key, value.
- * @param {function(string, *)} iteratorFn
- * @returns {function(*, string)}
- */
-function reverseParams(iteratorFn) {
- return function(value, key) { iteratorFn(key, value); };
-}
-
-/**
- * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
- * characters such as '012ABC'. The reason why we are not using simply a number counter is that
- * the number string gets longer over time, and it can also overflow, where as the nextId
- * will grow much slower, it is a string, and it will never overflow.
- *
- * @returns an unique alpha-numeric string
- */
-function nextUid() {
- var index = uid.length;
- var digit;
-
- while(index) {
- index--;
- digit = uid[index].charCodeAt(0);
- if (digit == 57 /*'9'*/) {
- uid[index] = 'A';
- return uid.join('');
- }
- if (digit == 90 /*'Z'*/) {
- uid[index] = '0';
- } else {
- uid[index] = String.fromCharCode(digit + 1);
- return uid.join('');
- }
- }
- uid.unshift('0');
- return uid.join('');
-}
-
-
-/**
- * Set or clear the hashkey for an object.
- * @param obj object
- * @param h the hashkey (!truthy to delete the hashkey)
- */
-function setHashKey(obj, h) {
- if (h) {
- obj.$$hashKey = h;
- }
- else {
- delete obj.$$hashKey;
- }
-}
-
-/**
- * @ngdoc function
- * @name angular.extend
- * @function
- *
- * @description
- * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
- * to `dst`. You can specify multiple `src` objects.
- *
- * @param {Object} dst Destination object.
- * @param {...Object} src Source object(s).
- * @returns {Object} Reference to `dst`.
- */
-function extend(dst) {
- var h = dst.$$hashKey;
- forEach(arguments, function(obj){
- if (obj !== dst) {
- forEach(obj, function(value, key){
- dst[key] = value;
- });
- }
- });
-
- setHashKey(dst,h);
- return dst;
-}
-
-function int(str) {
- return parseInt(str, 10);
-}
-
-
-function inherit(parent, extra) {
- return extend(new (extend(function() {}, {prototype:parent}))(), extra);
-}
-
-/**
- * @ngdoc function
- * @name angular.noop
- * @function
- *
- * @description
- * A function that performs no operations. This function can be useful when writing code in the
- * functional style.
-
- function foo(callback) {
- var result = calculateResult();
- (callback || angular.noop)(result);
- }
-
- */
-function noop() {}
-noop.$inject = [];
-
-
-/**
- * @ngdoc function
- * @name angular.identity
- * @function
- *
- * @description
- * A function that returns its first argument. This function is useful when writing code in the
- * functional style.
- *
-
- */
-function identity($) {return $;}
-identity.$inject = [];
-
-
-function valueFn(value) {return function() {return value;};}
-
-/**
- * @ngdoc function
- * @name angular.isUndefined
- * @function
- *
- * @description
- * Determines if a reference is undefined.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is undefined.
- */
-function isUndefined(value){return typeof value === 'undefined';}
-
-
-/**
- * @ngdoc function
- * @name angular.isDefined
- * @function
- *
- * @description
- * Determines if a reference is defined.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is defined.
- */
-function isDefined(value){return typeof value !== 'undefined';}
-
-
-/**
- * @ngdoc function
- * @name angular.isObject
- * @function
- *
- * @description
- * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
- * considered to be objects.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is an `Object` but not `null`.
- */
-function isObject(value){return value != null && typeof value === 'object';}
-
-
-/**
- * @ngdoc function
- * @name angular.isString
- * @function
- *
- * @description
- * Determines if a reference is a `String`.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is a `String`.
- */
-function isString(value){return typeof value === 'string';}
-
-
-/**
- * @ngdoc function
- * @name angular.isNumber
- * @function
- *
- * @description
- * Determines if a reference is a `Number`.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is a `Number`.
- */
-function isNumber(value){return typeof value === 'number';}
-
-
-/**
- * @ngdoc function
- * @name angular.isDate
- * @function
- *
- * @description
- * Determines if a value is a date.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is a `Date`.
- */
-function isDate(value){
- return toString.call(value) === '[object Date]';
-}
-
-
-/**
- * @ngdoc function
- * @name angular.isArray
- * @function
- *
- * @description
- * Determines if a reference is an `Array`.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is an `Array`.
- */
-function isArray(value) {
- return toString.call(value) === '[object Array]';
-}
-
-
-/**
- * @ngdoc function
- * @name angular.isFunction
- * @function
- *
- * @description
- * Determines if a reference is a `Function`.
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is a `Function`.
- */
-function isFunction(value){return typeof value === 'function';}
-
-
-/**
- * Determines if a value is a regular expression object.
- *
- * @private
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is a `RegExp`.
- */
-function isRegExp(value) {
- return toString.call(value) === '[object RegExp]';
-}
-
-
-/**
- * Checks if `obj` is a window object.
- *
- * @private
- * @param {*} obj Object to check
- * @returns {boolean} True if `obj` is a window obj.
- */
-function isWindow(obj) {
- return obj && obj.document && obj.location && obj.alert && obj.setInterval;
-}
-
-
-function isScope(obj) {
- return obj && obj.$evalAsync && obj.$watch;
-}
-
-
-function isFile(obj) {
- return toString.call(obj) === '[object File]';
-}
-
-
-function isBoolean(value) {
- return typeof value === 'boolean';
-}
-
-
-var trim = (function() {
- // native trim is way faster: http://jsperf.com/angular-trim-test
- // but IE doesn't have it... :-(
- // TODO: we should move this into IE/ES5 polyfill
- if (!String.prototype.trim) {
- return function(value) {
- return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
- };
- }
- return function(value) {
- return isString(value) ? value.trim() : value;
- };
-})();
-
-
-/**
- * @ngdoc function
- * @name angular.isElement
- * @function
- *
- * @description
- * Determines if a reference is a DOM element (or wrapped jQuery element).
- *
- * @param {*} value Reference to check.
- * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
- */
-function isElement(node) {
- return !!(node &&
- (node.nodeName // we are a direct element
- || (node.on && node.find))); // we have an on and find method part of jQuery API
-}
-
-/**
- * @param str 'key1,key2,...'
- * @returns {object} in the form of {key1:true, key2:true, ...}
- */
-function makeMap(str){
- var obj = {}, items = str.split(","), i;
- for ( i = 0; i < items.length; i++ )
- obj[ items[i] ] = true;
- return obj;
-}
-
-
-if (msie < 9) {
- nodeName_ = function(element) {
- element = element.nodeName ? element : element[0];
- return (element.scopeName && element.scopeName != 'HTML')
- ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
- };
-} else {
- nodeName_ = function(element) {
- return element.nodeName ? element.nodeName : element[0].nodeName;
- };
-}
-
-
-function map(obj, iterator, context) {
- var results = [];
- forEach(obj, function(value, index, list) {
- results.push(iterator.call(context, value, index, list));
- });
- return results;
-}
-
-
-/**
- * @description
- * Determines the number of elements in an array, the number of properties an object has, or
- * the length of a string.
- *
- * Note: This function is used to augment the Object type in Angular expressions. See
- * {@link angular.Object} for more information about Angular arrays.
- *
- * @param {Object|Array|string} obj Object, array, or string to inspect.
- * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
- * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
- */
-function size(obj, ownPropsOnly) {
- var count = 0, key;
-
- if (isArray(obj) || isString(obj)) {
- return obj.length;
- } else if (isObject(obj)){
- for (key in obj)
- if (!ownPropsOnly || obj.hasOwnProperty(key))
- count++;
- }
-
- return count;
-}
-
-
-function includes(array, obj) {
- return indexOf(array, obj) != -1;
-}
-
-function indexOf(array, obj) {
- if (array.indexOf) return array.indexOf(obj);
-
- for (var i = 0; i < array.length; i++) {
- if (obj === array[i]) return i;
- }
- return -1;
-}
-
-function arrayRemove(array, value) {
- var index = indexOf(array, value);
- if (index >=0)
- array.splice(index, 1);
- return value;
-}
-
-function isLeafNode (node) {
- if (node) {
- switch (node.nodeName) {
- case "OPTION":
- case "PRE":
- case "TITLE":
- return true;
- }
- }
- return false;
-}
-
-/**
- * @ngdoc function
- * @name angular.copy
- * @function
- *
- * @description
- * Creates a deep copy of `source`, which should be an object or an array.
- *
- * * If no destination is supplied, a copy of the object or array is created.
- * * If a destination is provided, all of its elements (for array) or properties (for objects)
- * are deleted and then all elements/properties from the source are copied to it.
- * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
- * * If `source` is identical to 'destination' an exception will be thrown.
- *
- * @param {*} source The source that will be used to make a copy.
- * Can be any type, including primitives, `null`, and `undefined`.
- * @param {(Object|Array)=} destination Destination into which the source is copied. If
- * provided, must be of the same type as `source`.
- * @returns {*} The copy or updated `destination`, if `destination` was specified.
- *
- * @example
-
-
-
-
-
form = {{user | json}}
-
master = {{master | json}}
-
-
-
-
-
- */
-function copy(source, destination){
- if (isWindow(source) || isScope(source)) {
- throw ngMinErr('cpws',
- "Can't copy! Making copies of Window or Scope instances is not supported.");
- }
-
- if (!destination) {
- destination = source;
- if (source) {
- if (isArray(source)) {
- destination = copy(source, []);
- } else if (isDate(source)) {
- destination = new Date(source.getTime());
- } else if (isRegExp(source)) {
- destination = new RegExp(source.source);
- } else if (isObject(source)) {
- destination = copy(source, {});
- }
- }
- } else {
- if (source === destination) throw ngMinErr('cpi',
- "Can't copy! Source and destination are identical.");
- if (isArray(source)) {
- destination.length = 0;
- for ( var i = 0; i < source.length; i++) {
- destination.push(copy(source[i]));
- }
- } else {
- var h = destination.$$hashKey;
- forEach(destination, function(value, key){
- delete destination[key];
- });
- for ( var key in source) {
- destination[key] = copy(source[key]);
- }
- setHashKey(destination,h);
- }
- }
- return destination;
-}
-
-/**
- * Create a shallow copy of an object
- */
-function shallowCopy(src, dst) {
- dst = dst || {};
-
- for(var key in src) {
- // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
- // so we don't need to worry about using our custom hasOwnProperty here
- if (src.hasOwnProperty(key) && key.charAt(0) !== '$' && key.charAt(1) !== '$') {
- dst[key] = src[key];
- }
- }
-
- return dst;
-}
-
-
-/**
- * @ngdoc function
- * @name angular.equals
- * @function
- *
- * @description
- * Determines if two objects or two values are equivalent. Supports value types, regular
- * expressions, arrays and objects.
- *
- * Two objects or values are considered equivalent if at least one of the following is true:
- *
- * * Both objects or values pass `===` comparison.
- * * Both objects or values are of the same type and all of their properties are equal by
- * comparing them with `angular.equals`.
- * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
- * * Both values represent the same regular expression (In JavasScript,
- * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
- * representation matches).
- *
- * During a property comparison, properties of `function` type and properties with names
- * that begin with `$` are ignored.
- *
- * Scope and DOMWindow objects are being compared only by identify (`===`).
- *
- * @param {*} o1 Object or value to compare.
- * @param {*} o2 Object or value to compare.
- * @returns {boolean} True if arguments are equal.
- */
-function equals(o1, o2) {
- if (o1 === o2) return true;
- if (o1 === null || o2 === null) return false;
- if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
- var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
- if (t1 == t2) {
- if (t1 == 'object') {
- if (isArray(o1)) {
- if (!isArray(o2)) return false;
- if ((length = o1.length) == o2.length) {
- for(key=0; key 2 ? sliceArgs(arguments, 2) : [];
- if (isFunction(fn) && !(fn instanceof RegExp)) {
- return curryArgs.length
- ? function() {
- return arguments.length
- ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
- : fn.apply(self, curryArgs);
- }
- : function() {
- return arguments.length
- ? fn.apply(self, arguments)
- : fn.call(self);
- };
- } else {
- // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
- return fn;
- }
-}
-
-
-function toJsonReplacer(key, value) {
- var val = value;
-
- if (typeof key === 'string' && key.charAt(0) === '$') {
- val = undefined;
- } else if (isWindow(value)) {
- val = '$WINDOW';
- } else if (value && document === value) {
- val = '$DOCUMENT';
- } else if (isScope(value)) {
- val = '$SCOPE';
- }
-
- return val;
-}
-
-
-/**
- * @ngdoc function
- * @name angular.toJson
- * @function
- *
- * @description
- * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
- * stripped since angular uses this notation internally.
- *
- * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
- * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
- * @returns {string|undefined} JSON-ified string representing `obj`.
- */
-function toJson(obj, pretty) {
- if (typeof obj === 'undefined') return undefined;
- return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
-}
-
-
-/**
- * @ngdoc function
- * @name angular.fromJson
- * @function
- *
- * @description
- * Deserializes a JSON string.
- *
- * @param {string} json JSON string to deserialize.
- * @returns {Object|Array|Date|string|number} Deserialized thingy.
- */
-function fromJson(json) {
- return isString(json)
- ? JSON.parse(json)
- : json;
-}
-
-
-function toBoolean(value) {
- if (typeof value === 'function') {
- value = true;
- } else if (value && value.length !== 0) {
- var v = lowercase("" + value);
- value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
- } else {
- value = false;
- }
- return value;
-}
-
-/**
- * @returns {string} Returns the string representation of the element.
- */
-function startingTag(element) {
- element = jqLite(element).clone();
- try {
- // turns out IE does not let you set .html() on elements which
- // are not allowed to have children. So we just ignore it.
- element.empty();
- } catch(e) {}
- // As Per DOM Standards
- var TEXT_NODE = 3;
- var elemHtml = jqLite('
').append(element).html();
- try {
- return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
- elemHtml.
- match(/^(<[^>]+>)/)[1].
- replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
- } catch(e) {
- return lowercase(elemHtml);
- }
-
-}
-
-
-/////////////////////////////////////////////////
-
-/**
- * Tries to decode the URI component without throwing an exception.
- *
- * @private
- * @param str value potential URI component to check.
- * @returns {boolean} True if `value` can be decoded
- * with the decodeURIComponent function.
- */
-function tryDecodeURIComponent(value) {
- try {
- return decodeURIComponent(value);
- } catch(e) {
- // Ignore any invalid uri component
- }
-}
-
-
-/**
- * Parses an escaped url query string into key-value pairs.
- * @returns Object.<(string|boolean)>
- */
-function parseKeyValue(/**string*/keyValue) {
- var obj = {}, key_value, key;
- forEach((keyValue || "").split('&'), function(keyValue){
- if ( keyValue ) {
- key_value = keyValue.split('=');
- key = tryDecodeURIComponent(key_value[0]);
- if ( isDefined(key) ) {
- var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
- if (!obj[key]) {
- obj[key] = val;
- } else if(isArray(obj[key])) {
- obj[key].push(val);
- } else {
- obj[key] = [obj[key],val];
- }
- }
- }
- });
- return obj;
-}
-
-function toKeyValue(obj) {
- var parts = [];
- forEach(obj, function(value, key) {
- if (isArray(value)) {
- forEach(value, function(arrayValue) {
- parts.push(encodeUriQuery(key, true) +
- (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
- });
- } else {
- parts.push(encodeUriQuery(key, true) +
- (value === true ? '' : '=' + encodeUriQuery(value, true)));
- }
- });
- return parts.length ? parts.join('&') : '';
-}
-
-
-/**
- * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
- * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
- * segments:
- * segment = *pchar
- * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
- * pct-encoded = "%" HEXDIG HEXDIG
- * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
- * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
- * / "*" / "+" / "," / ";" / "="
- */
-function encodeUriSegment(val) {
- return encodeUriQuery(val, true).
- replace(/%26/gi, '&').
- replace(/%3D/gi, '=').
- replace(/%2B/gi, '+');
-}
-
-
-/**
- * This method is intended for encoding *key* or *value* parts of query component. We need a custom
- * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
- * encoded per http://tools.ietf.org/html/rfc3986:
- * query = *( pchar / "/" / "?" )
- * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
- * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
- * pct-encoded = "%" HEXDIG HEXDIG
- * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
- * / "*" / "+" / "," / ";" / "="
- */
-function encodeUriQuery(val, pctEncodeSpaces) {
- return encodeURIComponent(val).
- replace(/%40/gi, '@').
- replace(/%3A/gi, ':').
- replace(/%24/g, '$').
- replace(/%2C/gi, ',').
- replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
-}
-
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngApp
- *
- * @element ANY
- * @param {angular.Module} ngApp an optional application
- * {@link angular.module module} name to load.
- *
- * @description
- *
- * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
- * designates the **root element** of the application and is typically placed near the root element
- * of the page - e.g. on the `` or `` tags.
- *
- * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
- * found in the document will be used to define the root element to auto-bootstrap as an
- * application. To run multiple applications in an HTML document you must manually bootstrap them using
- * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
- *
- * You can specify an **AngularJS module** to be used as the root module for the application. This
- * module will be loaded into the {@link AUTO.$injector} when the application is bootstrapped and
- * should contain the application code needed or have dependencies on other modules that will
- * contain the code. See {@link angular.module} for more information.
- *
- * In the example below if the `ngApp` directive were not placed on the `html` element then the
- * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
- * would not be resolved to `3`.
- *
- * `ngApp` is the easiest, and most common, way to bootstrap an application.
- *
-
-
-
- I can add: {{a}} + {{b}} = {{ a+b }}
-
-
- angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
- $scope.a = 1;
- $scope.b = 2;
- });
-
-
- *
- */
-function angularInit(element, bootstrap) {
- var elements = [element],
- appElement,
- module,
- names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
- NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
-
- function append(element) {
- element && elements.push(element);
- }
-
- forEach(names, function(name) {
- names[name] = true;
- append(document.getElementById(name));
- name = name.replace(':', '\\:');
- if (element.querySelectorAll) {
- forEach(element.querySelectorAll('.' + name), append);
- forEach(element.querySelectorAll('.' + name + '\\:'), append);
- forEach(element.querySelectorAll('[' + name + ']'), append);
- }
- });
-
- forEach(elements, function(element) {
- if (!appElement) {
- var className = ' ' + element.className + ' ';
- var match = NG_APP_CLASS_REGEXP.exec(className);
- if (match) {
- appElement = element;
- module = (match[2] || '').replace(/\s+/g, ',');
- } else {
- forEach(element.attributes, function(attr) {
- if (!appElement && names[attr.name]) {
- appElement = element;
- module = attr.value;
- }
- });
- }
- }
- });
- if (appElement) {
- bootstrap(appElement, module ? [module] : []);
- }
-}
-
-/**
- * @ngdoc function
- * @name angular.bootstrap
- * @description
- * Use this function to manually start up angular application.
- *
- * See: {@link guide/bootstrap Bootstrap}
- *
- * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
- * They must use {@link api/ng.directive:ngApp ngApp}.
- *
- * @param {Element} element DOM element which is the root of angular application.
- * @param {Array=} modules an array of modules to load into the application.
- * Each item in the array should be the name of a predefined module or a (DI annotated)
- * function that will be invoked by the injector as a run block.
- * See: {@link angular.module modules}
- * @returns {AUTO.$injector} Returns the newly created injector for this app.
- */
-function bootstrap(element, modules) {
- var doBootstrap = function() {
- element = jqLite(element);
-
- if (element.injector()) {
- var tag = (element[0] === document) ? 'document' : startingTag(element);
- throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
- }
-
- modules = modules || [];
- modules.unshift(['$provide', function($provide) {
- $provide.value('$rootElement', element);
- }]);
- modules.unshift('ng');
- var injector = createInjector(modules);
- injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
- function(scope, element, compile, injector, animate) {
- scope.$apply(function() {
- element.data('$injector', injector);
- compile(element)(scope);
- });
- }]
- );
- return injector;
- };
-
- var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
-
- if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
- return doBootstrap();
- }
-
- window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
- angular.resumeBootstrap = function(extraModules) {
- forEach(extraModules, function(module) {
- modules.push(module);
- });
- doBootstrap();
- };
-}
-
-var SNAKE_CASE_REGEXP = /[A-Z]/g;
-function snake_case(name, separator){
- separator = separator || '_';
- return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
- return (pos ? separator : '') + letter.toLowerCase();
- });
-}
-
-function bindJQuery() {
- // bind to jQuery if present;
- jQuery = window.jQuery;
- // reset to jQuery or default to us.
- if (jQuery) {
- jqLite = jQuery;
- extend(jQuery.fn, {
- scope: JQLitePrototype.scope,
- isolateScope: JQLitePrototype.isolateScope,
- controller: JQLitePrototype.controller,
- injector: JQLitePrototype.injector,
- inheritedData: JQLitePrototype.inheritedData
- });
- // Method signature:
- // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
- jqLitePatchJQueryRemove('remove', true, true, false);
- jqLitePatchJQueryRemove('empty', false, false, false);
- jqLitePatchJQueryRemove('html', false, false, true);
- } else {
- jqLite = JQLite;
- }
- angular.element = jqLite;
-}
-
-/**
- * throw error if the argument is falsy.
- */
-function assertArg(arg, name, reason) {
- if (!arg) {
- throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
- }
- return arg;
-}
-
-function assertArgFn(arg, name, acceptArrayAnnotation) {
- if (acceptArrayAnnotation && isArray(arg)) {
- arg = arg[arg.length - 1];
- }
-
- assertArg(isFunction(arg), name, 'not a function, got ' +
- (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
- return arg;
-}
-
-/**
- * throw error if the name given is hasOwnProperty
- * @param {String} name the name to test
- * @param {String} context the context in which the name is used, such as module or directive
- */
-function assertNotHasOwnProperty(name, context) {
- if (name === 'hasOwnProperty') {
- throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
- }
-}
-
-/**
- * Return the value accessible from the object by path. Any undefined traversals are ignored
- * @param {Object} obj starting object
- * @param {string} path path to traverse
- * @param {boolean=true} bindFnToScope
- * @returns value as accessible by path
- */
-//TODO(misko): this function needs to be removed
-function getter(obj, path, bindFnToScope) {
- if (!path) return obj;
- var keys = path.split('.');
- var key;
- var lastInstance = obj;
- var len = keys.length;
-
- for (var i = 0; i < len; i++) {
- key = keys[i];
- if (obj) {
- obj = (lastInstance = obj)[key];
- }
- }
- if (!bindFnToScope && isFunction(obj)) {
- return bind(lastInstance, obj);
- }
- return obj;
-}
-
-/**
- * Return the DOM siblings between the first and last node in the given array.
- * @param {Array} array like object
- * @returns jQlite object containing the elements
- */
-function getBlockElements(nodes) {
- var startNode = nodes[0],
- endNode = nodes[nodes.length - 1];
- if (startNode === endNode) {
- return jqLite(startNode);
- }
-
- var element = startNode;
- var elements = [element];
-
- do {
- element = element.nextSibling;
- if (!element) break;
- elements.push(element);
- } while (element !== endNode);
-
- return jqLite(elements);
-}
-
-/**
- * @ngdoc interface
- * @name angular.Module
- * @description
- *
- * Interface for configuring angular {@link angular.module modules}.
- */
-
-function setupModuleLoader(window) {
-
- var $injectorMinErr = minErr('$injector');
- var ngMinErr = minErr('ng');
-
- function ensure(obj, name, factory) {
- return obj[name] || (obj[name] = factory());
- }
-
- var angular = ensure(window, 'angular', Object);
-
- // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
- angular.$$minErr = angular.$$minErr || minErr;
-
- return ensure(angular, 'module', function() {
- /** @type {Object.} */
- var modules = {};
-
- /**
- * @ngdoc function
- * @name angular.module
- * @description
- *
- * The `angular.module` is a global place for creating, registering and retrieving Angular
- * modules.
- * All modules (angular core or 3rd party) that should be available to an application must be
- * registered using this mechanism.
- *
- * When passed two or more arguments, a new module is created. If passed only one argument, an
- * existing module (the name passed as the first argument to `module`) is retrieved.
- *
- *
- * # Module
- *
- * A module is a collection of services, directives, filters, and configuration information.
- * `angular.module` is used to configure the {@link AUTO.$injector $injector}.
- *
- *
- * // Create a new module
- * var myModule = angular.module('myModule', []);
- *
- * // register a new service
- * myModule.value('appName', 'MyCoolApp');
- *
- * // configure existing services inside initialization blocks.
- * myModule.config(function($locationProvider) {
- * // Configure existing providers
- * $locationProvider.hashPrefix('!');
- * });
- *
- *
- * Then you can create an injector and load your modules like this:
- *
- *
- * var injector = angular.injector(['ng', 'MyModule'])
- *
- *
- * However it's more likely that you'll just use
- * {@link ng.directive:ngApp ngApp} or
- * {@link angular.bootstrap} to simplify this process for you.
- *
- * @param {!string} name The name of the module to create or retrieve.
- * @param {Array.=} requires If specified then new module is being created. If
- * unspecified then the the module is being retrieved for further configuration.
- * @param {Function} configFn Optional configuration function for the module. Same as
- * {@link angular.Module#methods_config Module#config()}.
- * @returns {module} new module with the {@link angular.Module} api.
- */
- return function module(name, requires, configFn) {
- var assertNotHasOwnProperty = function(name, context) {
- if (name === 'hasOwnProperty') {
- throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
- }
- };
-
- assertNotHasOwnProperty(name, 'module');
- if (requires && modules.hasOwnProperty(name)) {
- modules[name] = null;
- }
- return ensure(modules, name, function() {
- if (!requires) {
- throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
- "the module name or forgot to load it. If registering a module ensure that you " +
- "specify the dependencies as the second argument.", name);
- }
-
- /** @type {!Array.>} */
- var invokeQueue = [];
-
- /** @type {!Array.} */
- var runBlocks = [];
-
- var config = invokeLater('$injector', 'invoke');
-
- /** @type {angular.Module} */
- var moduleInstance = {
- // Private state
- _invokeQueue: invokeQueue,
- _runBlocks: runBlocks,
-
- /**
- * @ngdoc property
- * @name angular.Module#requires
- * @propertyOf angular.Module
- * @returns {Array.} List of module names which must be loaded before this module.
- * @description
- * Holds the list of modules which the injector will load before the current module is
- * loaded.
- */
- requires: requires,
-
- /**
- * @ngdoc property
- * @name angular.Module#name
- * @propertyOf angular.Module
- * @returns {string} Name of the module.
- * @description
- */
- name: name,
-
-
- /**
- * @ngdoc method
- * @name angular.Module#provider
- * @methodOf angular.Module
- * @param {string} name service name
- * @param {Function} providerType Construction function for creating new instance of the
- * service.
- * @description
- * See {@link AUTO.$provide#provider $provide.provider()}.
- */
- provider: invokeLater('$provide', 'provider'),
-
- /**
- * @ngdoc method
- * @name angular.Module#factory
- * @methodOf angular.Module
- * @param {string} name service name
- * @param {Function} providerFunction Function for creating new instance of the service.
- * @description
- * See {@link AUTO.$provide#factory $provide.factory()}.
- */
- factory: invokeLater('$provide', 'factory'),
-
- /**
- * @ngdoc method
- * @name angular.Module#service
- * @methodOf angular.Module
- * @param {string} name service name
- * @param {Function} constructor A constructor function that will be instantiated.
- * @description
- * See {@link AUTO.$provide#service $provide.service()}.
- */
- service: invokeLater('$provide', 'service'),
-
- /**
- * @ngdoc method
- * @name angular.Module#value
- * @methodOf angular.Module
- * @param {string} name service name
- * @param {*} object Service instance object.
- * @description
- * See {@link AUTO.$provide#value $provide.value()}.
- */
- value: invokeLater('$provide', 'value'),
-
- /**
- * @ngdoc method
- * @name angular.Module#constant
- * @methodOf angular.Module
- * @param {string} name constant name
- * @param {*} object Constant value.
- * @description
- * Because the constant are fixed, they get applied before other provide methods.
- * See {@link AUTO.$provide#constant $provide.constant()}.
- */
- constant: invokeLater('$provide', 'constant', 'unshift'),
-
- /**
- * @ngdoc method
- * @name angular.Module#animation
- * @methodOf angular.Module
- * @param {string} name animation name
- * @param {Function} animationFactory Factory function for creating new instance of an
- * animation.
- * @description
- *
- * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
- *
- *
- * Defines an animation hook that can be later used with
- * {@link ngAnimate.$animate $animate} service and directives that use this service.
- *
- *
- * module.animation('.animation-name', function($inject1, $inject2) {
- * return {
- * eventName : function(element, done) {
- * //code to run the animation
- * //once complete, then run done()
- * return function cancellationFunction(element) {
- * //code to cancel the animation
- * }
- * }
- * }
- * })
- *
- *
- * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
- * {@link ngAnimate ngAnimate module} for more information.
- */
- animation: invokeLater('$animateProvider', 'register'),
-
- /**
- * @ngdoc method
- * @name angular.Module#filter
- * @methodOf angular.Module
- * @param {string} name Filter name.
- * @param {Function} filterFactory Factory function for creating new instance of filter.
- * @description
- * See {@link ng.$filterProvider#register $filterProvider.register()}.
- */
- filter: invokeLater('$filterProvider', 'register'),
-
- /**
- * @ngdoc method
- * @name angular.Module#controller
- * @methodOf angular.Module
- * @param {string|Object} name Controller name, or an object map of controllers where the
- * keys are the names and the values are the constructors.
- * @param {Function} constructor Controller constructor function.
- * @description
- * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
- */
- controller: invokeLater('$controllerProvider', 'register'),
-
- /**
- * @ngdoc method
- * @name angular.Module#directive
- * @methodOf angular.Module
- * @param {string|Object} name Directive name, or an object map of directives where the
- * keys are the names and the values are the factories.
- * @param {Function} directiveFactory Factory function for creating new instance of
- * directives.
- * @description
- * See {@link ng.$compileProvider#methods_directive $compileProvider.directive()}.
- */
- directive: invokeLater('$compileProvider', 'directive'),
-
- /**
- * @ngdoc method
- * @name angular.Module#config
- * @methodOf angular.Module
- * @param {Function} configFn Execute this function on module load. Useful for service
- * configuration.
- * @description
- * Use this method to register work which needs to be performed on module loading.
- */
- config: config,
-
- /**
- * @ngdoc method
- * @name angular.Module#run
- * @methodOf angular.Module
- * @param {Function} initializationFn Execute this function after injector creation.
- * Useful for application initialization.
- * @description
- * Use this method to register work which should be performed when the injector is done
- * loading all modules.
- */
- run: function(block) {
- runBlocks.push(block);
- return this;
- }
- };
-
- if (configFn) {
- config(configFn);
- }
-
- return moduleInstance;
-
- /**
- * @param {string} provider
- * @param {string} method
- * @param {String=} insertMethod
- * @returns {angular.Module}
- */
- function invokeLater(provider, method, insertMethod) {
- return function() {
- invokeQueue[insertMethod || 'push']([provider, method, arguments]);
- return moduleInstance;
- };
- }
- });
- };
- });
-
-}
-
-/* global
- angularModule: true,
- version: true,
-
- $LocaleProvider,
- $CompileProvider,
-
- htmlAnchorDirective,
- inputDirective,
- inputDirective,
- formDirective,
- scriptDirective,
- selectDirective,
- styleDirective,
- optionDirective,
- ngBindDirective,
- ngBindHtmlDirective,
- ngBindTemplateDirective,
- ngClassDirective,
- ngClassEvenDirective,
- ngClassOddDirective,
- ngCspDirective,
- ngCloakDirective,
- ngControllerDirective,
- ngFormDirective,
- ngHideDirective,
- ngIfDirective,
- ngIncludeDirective,
- ngIncludeFillContentDirective,
- ngInitDirective,
- ngNonBindableDirective,
- ngPluralizeDirective,
- ngRepeatDirective,
- ngShowDirective,
- ngStyleDirective,
- ngSwitchDirective,
- ngSwitchWhenDirective,
- ngSwitchDefaultDirective,
- ngOptionsDirective,
- ngTranscludeDirective,
- ngModelDirective,
- ngListDirective,
- ngChangeDirective,
- requiredDirective,
- requiredDirective,
- ngValueDirective,
- ngAttributeAliasDirectives,
- ngEventDirectives,
-
- $AnchorScrollProvider,
- $AnimateProvider,
- $BrowserProvider,
- $CacheFactoryProvider,
- $ControllerProvider,
- $DocumentProvider,
- $ExceptionHandlerProvider,
- $FilterProvider,
- $InterpolateProvider,
- $IntervalProvider,
- $HttpProvider,
- $HttpBackendProvider,
- $LocationProvider,
- $LogProvider,
- $ParseProvider,
- $RootScopeProvider,
- $QProvider,
- $$SanitizeUriProvider,
- $SceProvider,
- $SceDelegateProvider,
- $SnifferProvider,
- $TemplateCacheProvider,
- $TimeoutProvider,
- $WindowProvider
-*/
-
-
-/**
- * @ngdoc property
- * @name angular.version
- * @description
- * An object that contains information about the current AngularJS version. This object has the
- * following properties:
- *
- * - `full` – `{string}` – Full version string, such as "0.9.18".
- * - `major` – `{number}` – Major version number, such as "0".
- * - `minor` – `{number}` – Minor version number, such as "9".
- * - `dot` – `{number}` – Dot version number, such as "18".
- * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
- */
-var version = {
- full: '1.2.9', // all of these placeholder strings will be replaced by grunt's
- major: 1, // package task
- minor: 2,
- dot: 9,
- codeName: 'enchanted-articulacy'
-};
-
-
-function publishExternalAPI(angular){
- extend(angular, {
- 'bootstrap': bootstrap,
- 'copy': copy,
- 'extend': extend,
- 'equals': equals,
- 'element': jqLite,
- 'forEach': forEach,
- 'injector': createInjector,
- 'noop':noop,
- 'bind':bind,
- 'toJson': toJson,
- 'fromJson': fromJson,
- 'identity':identity,
- 'isUndefined': isUndefined,
- 'isDefined': isDefined,
- 'isString': isString,
- 'isFunction': isFunction,
- 'isObject': isObject,
- 'isNumber': isNumber,
- 'isElement': isElement,
- 'isArray': isArray,
- 'version': version,
- 'isDate': isDate,
- 'lowercase': lowercase,
- 'uppercase': uppercase,
- 'callbacks': {counter: 0},
- '$$minErr': minErr,
- '$$csp': csp
- });
-
- angularModule = setupModuleLoader(window);
- try {
- angularModule('ngLocale');
- } catch (e) {
- angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
- }
-
- angularModule('ng', ['ngLocale'], ['$provide',
- function ngModule($provide) {
- // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
- $provide.provider({
- $$sanitizeUri: $$SanitizeUriProvider
- });
- $provide.provider('$compile', $CompileProvider).
- directive({
- a: htmlAnchorDirective,
- input: inputDirective,
- textarea: inputDirective,
- form: formDirective,
- script: scriptDirective,
- select: selectDirective,
- style: styleDirective,
- option: optionDirective,
- ngBind: ngBindDirective,
- ngBindHtml: ngBindHtmlDirective,
- ngBindTemplate: ngBindTemplateDirective,
- ngClass: ngClassDirective,
- ngClassEven: ngClassEvenDirective,
- ngClassOdd: ngClassOddDirective,
- ngCloak: ngCloakDirective,
- ngController: ngControllerDirective,
- ngForm: ngFormDirective,
- ngHide: ngHideDirective,
- ngIf: ngIfDirective,
- ngInclude: ngIncludeDirective,
- ngInit: ngInitDirective,
- ngNonBindable: ngNonBindableDirective,
- ngPluralize: ngPluralizeDirective,
- ngRepeat: ngRepeatDirective,
- ngShow: ngShowDirective,
- ngStyle: ngStyleDirective,
- ngSwitch: ngSwitchDirective,
- ngSwitchWhen: ngSwitchWhenDirective,
- ngSwitchDefault: ngSwitchDefaultDirective,
- ngOptions: ngOptionsDirective,
- ngTransclude: ngTranscludeDirective,
- ngModel: ngModelDirective,
- ngList: ngListDirective,
- ngChange: ngChangeDirective,
- required: requiredDirective,
- ngRequired: requiredDirective,
- ngValue: ngValueDirective
- }).
- directive({
- ngInclude: ngIncludeFillContentDirective
- }).
- directive(ngAttributeAliasDirectives).
- directive(ngEventDirectives);
- $provide.provider({
- $anchorScroll: $AnchorScrollProvider,
- $animate: $AnimateProvider,
- $browser: $BrowserProvider,
- $cacheFactory: $CacheFactoryProvider,
- $controller: $ControllerProvider,
- $document: $DocumentProvider,
- $exceptionHandler: $ExceptionHandlerProvider,
- $filter: $FilterProvider,
- $interpolate: $InterpolateProvider,
- $interval: $IntervalProvider,
- $http: $HttpProvider,
- $httpBackend: $HttpBackendProvider,
- $location: $LocationProvider,
- $log: $LogProvider,
- $parse: $ParseProvider,
- $rootScope: $RootScopeProvider,
- $q: $QProvider,
- $sce: $SceProvider,
- $sceDelegate: $SceDelegateProvider,
- $sniffer: $SnifferProvider,
- $templateCache: $TemplateCacheProvider,
- $timeout: $TimeoutProvider,
- $window: $WindowProvider
- });
- }
- ]);
-}
-
-/* global
-
- -JQLitePrototype,
- -addEventListenerFn,
- -removeEventListenerFn,
- -BOOLEAN_ATTR
-*/
-
-//////////////////////////////////
-//JQLite
-//////////////////////////////////
-
-/**
- * @ngdoc function
- * @name angular.element
- * @function
- *
- * @description
- * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
- *
- * If jQuery is available, `angular.element` is an alias for the
- * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
- * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
- *
- *
jqLite is a tiny, API-compatible subset of jQuery that allows
- * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
- * commonly needed functionality with the goal of having a very small footprint.
- *
- * To use jQuery, simply load it before `DOMContentLoaded` event fired.
- *
- *
**Note:** all element references in Angular are always wrapped with jQuery or
- * jqLite; they are never raw DOM references.
- *
- * ## Angular's jqLite
- * jqLite provides only the following jQuery methods:
- *
- * - [`addClass()`](http://api.jquery.com/addClass/)
- * - [`after()`](http://api.jquery.com/after/)
- * - [`append()`](http://api.jquery.com/append/)
- * - [`attr()`](http://api.jquery.com/attr/)
- * - [`bind()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
- * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
- * - [`clone()`](http://api.jquery.com/clone/)
- * - [`contents()`](http://api.jquery.com/contents/)
- * - [`css()`](http://api.jquery.com/css/)
- * - [`data()`](http://api.jquery.com/data/)
- * - [`empty()`](http://api.jquery.com/empty/)
- * - [`eq()`](http://api.jquery.com/eq/)
- * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
- * - [`hasClass()`](http://api.jquery.com/hasClass/)
- * - [`html()`](http://api.jquery.com/html/)
- * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
- * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
- * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
- * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
- * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
- * - [`prepend()`](http://api.jquery.com/prepend/)
- * - [`prop()`](http://api.jquery.com/prop/)
- * - [`ready()`](http://api.jquery.com/ready/)
- * - [`remove()`](http://api.jquery.com/remove/)
- * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
- * - [`removeClass()`](http://api.jquery.com/removeClass/)
- * - [`removeData()`](http://api.jquery.com/removeData/)
- * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
- * - [`text()`](http://api.jquery.com/text/)
- * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
- * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
- * - [`unbind()`](http://api.jquery.com/off/) - Does not support namespaces
- * - [`val()`](http://api.jquery.com/val/)
- * - [`wrap()`](http://api.jquery.com/wrap/)
- *
- * ## jQuery/jqLite Extras
- * Angular also provides the following additional methods and events to both jQuery and jqLite:
- *
- * ### Events
- * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
- * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
- * element before it is removed.
- *
- * ### Methods
- * - `controller(name)` - retrieves the controller of the current element or its parent. By default
- * retrieves controller associated with the `ngController` directive. If `name` is provided as
- * camelCase directive name, then the controller for this directive will be retrieved (e.g.
- * `'ngModel'`).
- * - `injector()` - retrieves the injector of the current element or its parent.
- * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
- * element or its parent.
- * - `isolateScope()` - retrieves an isolate {@link api/ng.$rootScope.Scope scope} if one is attached directly to the
- * current element. This getter should be used only on elements that contain a directive which starts a new isolate
- * scope. Calling `scope()` on this element always returns the original non-isolate scope.
- * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
- * parent element is reached.
- *
- * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
- * @returns {Object} jQuery object.
- */
-
-var jqCache = JQLite.cache = {},
- jqName = JQLite.expando = 'ng-' + new Date().getTime(),
- jqId = 1,
- addEventListenerFn = (window.document.addEventListener
- ? function(element, type, fn) {element.addEventListener(type, fn, false);}
- : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
- removeEventListenerFn = (window.document.removeEventListener
- ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
- : function(element, type, fn) {element.detachEvent('on' + type, fn); });
-
-function jqNextId() { return ++jqId; }
-
-
-var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
-var MOZ_HACK_REGEXP = /^moz([A-Z])/;
-var jqLiteMinErr = minErr('jqLite');
-
-/**
- * Converts snake_case to camelCase.
- * Also there is special case for Moz prefix starting with upper case letter.
- * @param name Name to normalize
- */
-function camelCase(name) {
- return name.
- replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
- return offset ? letter.toUpperCase() : letter;
- }).
- replace(MOZ_HACK_REGEXP, 'Moz$1');
-}
-
-/////////////////////////////////////////////
-// jQuery mutation patch
-//
-// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
-// $destroy event on all DOM nodes being removed.
-//
-/////////////////////////////////////////////
-
-function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
- var originalJqFn = jQuery.fn[name];
- originalJqFn = originalJqFn.$original || originalJqFn;
- removePatch.$original = originalJqFn;
- jQuery.fn[name] = removePatch;
-
- function removePatch(param) {
- // jshint -W040
- var list = filterElems && param ? [this.filter(param)] : [this],
- fireEvent = dispatchThis,
- set, setIndex, setLength,
- element, childIndex, childLength, children;
-
- if (!getterIfNoArguments || param != null) {
- while(list.length) {
- set = list.shift();
- for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
- element = jqLite(set[setIndex]);
- if (fireEvent) {
- element.triggerHandler('$destroy');
- } else {
- fireEvent = !fireEvent;
- }
- for(childIndex = 0, childLength = (children = element.children()).length;
- childIndex < childLength;
- childIndex++) {
- list.push(jQuery(children[childIndex]));
- }
- }
- }
- }
- return originalJqFn.apply(this, arguments);
- }
-}
-
-/////////////////////////////////////////////
-function JQLite(element) {
- if (element instanceof JQLite) {
- return element;
- }
- if (!(this instanceof JQLite)) {
- if (isString(element) && element.charAt(0) != '<') {
- throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
- }
- return new JQLite(element);
- }
-
- if (isString(element)) {
- var div = document.createElement('div');
- // Read about the NoScope elements here:
- // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
- div.innerHTML = '
' + element; // IE insanity to make NoScope elements work!
- div.removeChild(div.firstChild); // remove the superfluous div
- jqLiteAddNodes(this, div.childNodes);
- var fragment = jqLite(document.createDocumentFragment());
- fragment.append(this); // detach the elements from the temporary DOM div.
- } else {
- jqLiteAddNodes(this, element);
- }
-}
-
-function jqLiteClone(element) {
- return element.cloneNode(true);
-}
-
-function jqLiteDealoc(element){
- jqLiteRemoveData(element);
- for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
- jqLiteDealoc(children[i]);
- }
-}
-
-function jqLiteOff(element, type, fn, unsupported) {
- if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
-
- var events = jqLiteExpandoStore(element, 'events'),
- handle = jqLiteExpandoStore(element, 'handle');
-
- if (!handle) return; //no listeners registered
-
- if (isUndefined(type)) {
- forEach(events, function(eventHandler, type) {
- removeEventListenerFn(element, type, eventHandler);
- delete events[type];
- });
- } else {
- forEach(type.split(' '), function(type) {
- if (isUndefined(fn)) {
- removeEventListenerFn(element, type, events[type]);
- delete events[type];
- } else {
- arrayRemove(events[type] || [], fn);
- }
- });
- }
-}
-
-function jqLiteRemoveData(element, name) {
- var expandoId = element[jqName],
- expandoStore = jqCache[expandoId];
-
- if (expandoStore) {
- if (name) {
- delete jqCache[expandoId].data[name];
- return;
- }
-
- if (expandoStore.handle) {
- expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
- jqLiteOff(element);
- }
- delete jqCache[expandoId];
- element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
- }
-}
-
-function jqLiteExpandoStore(element, key, value) {
- var expandoId = element[jqName],
- expandoStore = jqCache[expandoId || -1];
-
- if (isDefined(value)) {
- if (!expandoStore) {
- element[jqName] = expandoId = jqNextId();
- expandoStore = jqCache[expandoId] = {};
- }
- expandoStore[key] = value;
- } else {
- return expandoStore && expandoStore[key];
- }
-}
-
-function jqLiteData(element, key, value) {
- var data = jqLiteExpandoStore(element, 'data'),
- isSetter = isDefined(value),
- keyDefined = !isSetter && isDefined(key),
- isSimpleGetter = keyDefined && !isObject(key);
-
- if (!data && !isSimpleGetter) {
- jqLiteExpandoStore(element, 'data', data = {});
- }
-
- if (isSetter) {
- data[key] = value;
- } else {
- if (keyDefined) {
- if (isSimpleGetter) {
- // don't create data in this case.
- return data && data[key];
- } else {
- extend(data, key);
- }
- } else {
- return data;
- }
- }
-}
-
-function jqLiteHasClass(element, selector) {
- if (!element.getAttribute) return false;
- return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
- indexOf( " " + selector + " " ) > -1);
-}
-
-function jqLiteRemoveClass(element, cssClasses) {
- if (cssClasses && element.setAttribute) {
- forEach(cssClasses.split(' '), function(cssClass) {
- element.setAttribute('class', trim(
- (" " + (element.getAttribute('class') || '') + " ")
- .replace(/[\n\t]/g, " ")
- .replace(" " + trim(cssClass) + " ", " "))
- );
- });
- }
-}
-
-function jqLiteAddClass(element, cssClasses) {
- if (cssClasses && element.setAttribute) {
- var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
- .replace(/[\n\t]/g, " ");
-
- forEach(cssClasses.split(' '), function(cssClass) {
- cssClass = trim(cssClass);
- if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
- existingClasses += cssClass + ' ';
- }
- });
-
- element.setAttribute('class', trim(existingClasses));
- }
-}
-
-function jqLiteAddNodes(root, elements) {
- if (elements) {
- elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
- ? elements
- : [ elements ];
- for(var i=0; i < elements.length; i++) {
- root.push(elements[i]);
- }
- }
-}
-
-function jqLiteController(element, name) {
- return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
-}
-
-function jqLiteInheritedData(element, name, value) {
- element = jqLite(element);
-
- // if element is the document object work with the html element instead
- // this makes $(document).scope() possible
- if(element[0].nodeType == 9) {
- element = element.find('html');
- }
- var names = isArray(name) ? name : [name];
-
- while (element.length) {
-
- for (var i = 0, ii = names.length; i < ii; i++) {
- if ((value = element.data(names[i])) !== undefined) return value;
- }
- element = element.parent();
- }
-}
-
-function jqLiteEmpty(element) {
- for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
- jqLiteDealoc(childNodes[i]);
- }
- while (element.firstChild) {
- element.removeChild(element.firstChild);
- }
-}
-
-//////////////////////////////////////////
-// Functions which are declared directly.
-//////////////////////////////////////////
-var JQLitePrototype = JQLite.prototype = {
- ready: function(fn) {
- var fired = false;
-
- function trigger() {
- if (fired) return;
- fired = true;
- fn();
- }
-
- // check if document already is loaded
- if (document.readyState === 'complete'){
- setTimeout(trigger);
- } else {
- this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
- // we can not use jqLite since we are not done loading and jQuery could be loaded later.
- // jshint -W064
- JQLite(window).on('load', trigger); // fallback to window.onload for others
- // jshint +W064
- }
- },
- toString: function() {
- var value = [];
- forEach(this, function(e){ value.push('' + e);});
- return '[' + value.join(', ') + ']';
- },
-
- eq: function(index) {
- return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
- },
-
- length: 0,
- push: push,
- sort: [].sort,
- splice: [].splice
-};
-
-//////////////////////////////////////////
-// Functions iterating getter/setters.
-// these functions return self on setter and
-// value on get.
-//////////////////////////////////////////
-var BOOLEAN_ATTR = {};
-forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
- BOOLEAN_ATTR[lowercase(value)] = value;
-});
-var BOOLEAN_ELEMENTS = {};
-forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
- BOOLEAN_ELEMENTS[uppercase(value)] = true;
-});
-
-function getBooleanAttrName(element, name) {
- // check dom last since we will most likely fail on name
- var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
-
- // booleanAttr is here twice to minimize DOM access
- return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
-}
-
-forEach({
- data: jqLiteData,
- inheritedData: jqLiteInheritedData,
-
- scope: function(element) {
- // Can't use jqLiteData here directly so we stay compatible with jQuery!
- return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
- },
-
- isolateScope: function(element) {
- // Can't use jqLiteData here directly so we stay compatible with jQuery!
- return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
- },
-
- controller: jqLiteController ,
-
- injector: function(element) {
- return jqLiteInheritedData(element, '$injector');
- },
-
- removeAttr: function(element,name) {
- element.removeAttribute(name);
- },
-
- hasClass: jqLiteHasClass,
-
- css: function(element, name, value) {
- name = camelCase(name);
-
- if (isDefined(value)) {
- element.style[name] = value;
- } else {
- var val;
-
- if (msie <= 8) {
- // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
- val = element.currentStyle && element.currentStyle[name];
- if (val === '') val = 'auto';
- }
-
- val = val || element.style[name];
-
- if (msie <= 8) {
- // jquery weirdness :-/
- val = (val === '') ? undefined : val;
- }
-
- return val;
- }
- },
-
- attr: function(element, name, value){
- var lowercasedName = lowercase(name);
- if (BOOLEAN_ATTR[lowercasedName]) {
- if (isDefined(value)) {
- if (!!value) {
- element[name] = true;
- element.setAttribute(name, lowercasedName);
- } else {
- element[name] = false;
- element.removeAttribute(lowercasedName);
- }
- } else {
- return (element[name] ||
- (element.attributes.getNamedItem(name)|| noop).specified)
- ? lowercasedName
- : undefined;
- }
- } else if (isDefined(value)) {
- element.setAttribute(name, value);
- } else if (element.getAttribute) {
- // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
- // some elements (e.g. Document) don't have get attribute, so return undefined
- var ret = element.getAttribute(name, 2);
- // normalize non-existing attributes to undefined (as jQuery)
- return ret === null ? undefined : ret;
- }
- },
-
- prop: function(element, name, value) {
- if (isDefined(value)) {
- element[name] = value;
- } else {
- return element[name];
- }
- },
-
- text: (function() {
- var NODE_TYPE_TEXT_PROPERTY = [];
- if (msie < 9) {
- NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
- NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
- } else {
- NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
- NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
- }
- getText.$dv = '';
- return getText;
-
- function getText(element, value) {
- var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
- if (isUndefined(value)) {
- return textProp ? element[textProp] : '';
- }
- element[textProp] = value;
- }
- })(),
-
- val: function(element, value) {
- if (isUndefined(value)) {
- if (nodeName_(element) === 'SELECT' && element.multiple) {
- var result = [];
- forEach(element.options, function (option) {
- if (option.selected) {
- result.push(option.value || option.text);
- }
- });
- return result.length === 0 ? null : result;
- }
- return element.value;
- }
- element.value = value;
- },
-
- html: function(element, value) {
- if (isUndefined(value)) {
- return element.innerHTML;
- }
- for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
- jqLiteDealoc(childNodes[i]);
- }
- element.innerHTML = value;
- },
-
- empty: jqLiteEmpty
-}, function(fn, name){
- /**
- * Properties: writes return selection, reads return first value
- */
- JQLite.prototype[name] = function(arg1, arg2) {
- var i, key;
-
- // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
- // in a way that survives minification.
- // jqLiteEmpty takes no arguments but is a setter.
- if (fn !== jqLiteEmpty &&
- (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
- if (isObject(arg1)) {
-
- // we are a write, but the object properties are the key/values
- for (i = 0; i < this.length; i++) {
- if (fn === jqLiteData) {
- // data() takes the whole object in jQuery
- fn(this[i], arg1);
- } else {
- for (key in arg1) {
- fn(this[i], key, arg1[key]);
- }
- }
- }
- // return self for chaining
- return this;
- } else {
- // we are a read, so read the first child.
- var value = fn.$dv;
- // Only if we have $dv do we iterate over all, otherwise it is just the first element.
- var jj = (value === undefined) ? Math.min(this.length, 1) : this.length;
- for (var j = 0; j < jj; j++) {
- var nodeValue = fn(this[j], arg1, arg2);
- value = value ? value + nodeValue : nodeValue;
- }
- return value;
- }
- } else {
- // we are a write, so apply to all children
- for (i = 0; i < this.length; i++) {
- fn(this[i], arg1, arg2);
- }
- // return self for chaining
- return this;
- }
- };
-});
-
-function createEventHandler(element, events) {
- var eventHandler = function (event, type) {
- if (!event.preventDefault) {
- event.preventDefault = function() {
- event.returnValue = false; //ie
- };
- }
-
- if (!event.stopPropagation) {
- event.stopPropagation = function() {
- event.cancelBubble = true; //ie
- };
- }
-
- if (!event.target) {
- event.target = event.srcElement || document;
- }
-
- if (isUndefined(event.defaultPrevented)) {
- var prevent = event.preventDefault;
- event.preventDefault = function() {
- event.defaultPrevented = true;
- prevent.call(event);
- };
- event.defaultPrevented = false;
- }
-
- event.isDefaultPrevented = function() {
- return event.defaultPrevented || event.returnValue === false;
- };
-
- // Copy event handlers in case event handlers array is modified during execution.
- var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
-
- forEach(eventHandlersCopy, function(fn) {
- fn.call(element, event);
- });
-
- // Remove monkey-patched methods (IE),
- // as they would cause memory leaks in IE8.
- if (msie <= 8) {
- // IE7/8 does not allow to delete property on native object
- event.preventDefault = null;
- event.stopPropagation = null;
- event.isDefaultPrevented = null;
- } else {
- // It shouldn't affect normal browsers (native methods are defined on prototype).
- delete event.preventDefault;
- delete event.stopPropagation;
- delete event.isDefaultPrevented;
- }
- };
- eventHandler.elem = element;
- return eventHandler;
-}
-
-//////////////////////////////////////////
-// Functions iterating traversal.
-// These functions chain results into a single
-// selector.
-//////////////////////////////////////////
-forEach({
- removeData: jqLiteRemoveData,
-
- dealoc: jqLiteDealoc,
-
- on: function onFn(element, type, fn, unsupported){
- if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
-
- var events = jqLiteExpandoStore(element, 'events'),
- handle = jqLiteExpandoStore(element, 'handle');
-
- if (!events) jqLiteExpandoStore(element, 'events', events = {});
- if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
-
- forEach(type.split(' '), function(type){
- var eventFns = events[type];
-
- if (!eventFns) {
- if (type == 'mouseenter' || type == 'mouseleave') {
- var contains = document.body.contains || document.body.compareDocumentPosition ?
- function( a, b ) {
- // jshint bitwise: false
- var adown = a.nodeType === 9 ? a.documentElement : a,
- bup = b && b.parentNode;
- return a === bup || !!( bup && bup.nodeType === 1 && (
- adown.contains ?
- adown.contains( bup ) :
- a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
- ));
- } :
- function( a, b ) {
- if ( b ) {
- while ( (b = b.parentNode) ) {
- if ( b === a ) {
- return true;
- }
- }
- }
- return false;
- };
-
- events[type] = [];
-
- // Refer to jQuery's implementation of mouseenter & mouseleave
- // Read about mouseenter and mouseleave:
- // http://www.quirksmode.org/js/events_mouse.html#link8
- var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
-
- onFn(element, eventmap[type], function(event) {
- var target = this, related = event.relatedTarget;
- // For mousenter/leave call the handler if related is outside the target.
- // NB: No relatedTarget if the mouse left/entered the browser window
- if ( !related || (related !== target && !contains(target, related)) ){
- handle(event, type);
- }
- });
-
- } else {
- addEventListenerFn(element, type, handle);
- events[type] = [];
- }
- eventFns = events[type];
- }
- eventFns.push(fn);
- });
- },
-
- off: jqLiteOff,
-
- one: function(element, type, fn) {
- element = jqLite(element);
-
- //add the listener twice so that when it is called
- //you can remove the original function and still be
- //able to call element.off(ev, fn) normally
- element.on(type, function onFn() {
- element.off(type, fn);
- element.off(type, onFn);
- });
- element.on(type, fn);
- },
-
- replaceWith: function(element, replaceNode) {
- var index, parent = element.parentNode;
- jqLiteDealoc(element);
- forEach(new JQLite(replaceNode), function(node){
- if (index) {
- parent.insertBefore(node, index.nextSibling);
- } else {
- parent.replaceChild(node, element);
- }
- index = node;
- });
- },
-
- children: function(element) {
- var children = [];
- forEach(element.childNodes, function(element){
- if (element.nodeType === 1)
- children.push(element);
- });
- return children;
- },
-
- contents: function(element) {
- return element.childNodes || [];
- },
-
- append: function(element, node) {
- forEach(new JQLite(node), function(child){
- if (element.nodeType === 1 || element.nodeType === 11) {
- element.appendChild(child);
- }
- });
- },
-
- prepend: function(element, node) {
- if (element.nodeType === 1) {
- var index = element.firstChild;
- forEach(new JQLite(node), function(child){
- element.insertBefore(child, index);
- });
- }
- },
-
- wrap: function(element, wrapNode) {
- wrapNode = jqLite(wrapNode)[0];
- var parent = element.parentNode;
- if (parent) {
- parent.replaceChild(wrapNode, element);
- }
- wrapNode.appendChild(element);
- },
-
- remove: function(element) {
- jqLiteDealoc(element);
- var parent = element.parentNode;
- if (parent) parent.removeChild(element);
- },
-
- after: function(element, newElement) {
- var index = element, parent = element.parentNode;
- forEach(new JQLite(newElement), function(node){
- parent.insertBefore(node, index.nextSibling);
- index = node;
- });
- },
-
- addClass: jqLiteAddClass,
- removeClass: jqLiteRemoveClass,
-
- toggleClass: function(element, selector, condition) {
- if (isUndefined(condition)) {
- condition = !jqLiteHasClass(element, selector);
- }
- (condition ? jqLiteAddClass : jqLiteRemoveClass)(element, selector);
- },
-
- parent: function(element) {
- var parent = element.parentNode;
- return parent && parent.nodeType !== 11 ? parent : null;
- },
-
- next: function(element) {
- if (element.nextElementSibling) {
- return element.nextElementSibling;
- }
-
- // IE8 doesn't have nextElementSibling
- var elm = element.nextSibling;
- while (elm != null && elm.nodeType !== 1) {
- elm = elm.nextSibling;
- }
- return elm;
- },
-
- find: function(element, selector) {
- if (element.getElementsByTagName) {
- return element.getElementsByTagName(selector);
- } else {
- return [];
- }
- },
-
- clone: jqLiteClone,
-
- triggerHandler: function(element, eventName, eventData) {
- var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
-
- eventData = eventData || [];
-
- var event = [{
- preventDefault: noop,
- stopPropagation: noop
- }];
-
- forEach(eventFns, function(fn) {
- fn.apply(element, event.concat(eventData));
- });
- }
-}, function(fn, name){
- /**
- * chaining functions
- */
- JQLite.prototype[name] = function(arg1, arg2, arg3) {
- var value;
- for(var i=0; i < this.length; i++) {
- if (isUndefined(value)) {
- value = fn(this[i], arg1, arg2, arg3);
- if (isDefined(value)) {
- // any function which returns a value needs to be wrapped
- value = jqLite(value);
- }
- } else {
- jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
- }
- }
- return isDefined(value) ? value : this;
- };
-
- // bind legacy bind/unbind to on/off
- JQLite.prototype.bind = JQLite.prototype.on;
- JQLite.prototype.unbind = JQLite.prototype.off;
-});
-
-/**
- * Computes a hash of an 'obj'.
- * Hash of a:
- * string is string
- * number is number as string
- * object is either result of calling $$hashKey function on the object or uniquely generated id,
- * that is also assigned to the $$hashKey property of the object.
- *
- * @param obj
- * @returns {string} hash string such that the same input will have the same hash string.
- * The resulting string key is in 'type:hashKey' format.
- */
-function hashKey(obj) {
- var objType = typeof obj,
- key;
-
- if (objType == 'object' && obj !== null) {
- if (typeof (key = obj.$$hashKey) == 'function') {
- // must invoke on object to keep the right this
- key = obj.$$hashKey();
- } else if (key === undefined) {
- key = obj.$$hashKey = nextUid();
- }
- } else {
- key = obj;
- }
-
- return objType + ':' + key;
-}
-
-/**
- * HashMap which can use objects as keys
- */
-function HashMap(array){
- forEach(array, this.put, this);
-}
-HashMap.prototype = {
- /**
- * Store key value pair
- * @param key key to store can be any type
- * @param value value to store can be any type
- */
- put: function(key, value) {
- this[hashKey(key)] = value;
- },
-
- /**
- * @param key
- * @returns the value for the key
- */
- get: function(key) {
- return this[hashKey(key)];
- },
-
- /**
- * Remove the key/value pair
- * @param key
- */
- remove: function(key) {
- var value = this[key = hashKey(key)];
- delete this[key];
- return value;
- }
-};
-
-/**
- * @ngdoc function
- * @name angular.injector
- * @function
- *
- * @description
- * Creates an injector function that can be used for retrieving services as well as for
- * dependency injection (see {@link guide/di dependency injection}).
- *
-
- * @param {Array.} modules A list of module functions or their aliases. See
- * {@link angular.module}. The `ng` module must be explicitly added.
- * @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
- *
- * @example
- * Typical usage
- *
- * // create an injector
- * var $injector = angular.injector(['ng']);
- *
- * // use the injector to kick off your application
- * // use the type inference to auto inject arguments, or use implicit injection
- * $injector.invoke(function($rootScope, $compile, $document){
- * $compile($document)($rootScope);
- * $rootScope.$digest();
- * });
- *
- *
- * Sometimes you want to get access to the injector of a currently running Angular app
- * from outside Angular. Perhaps, you want to inject and compile some markup after the
- * application has been bootstrapped. You can do this using extra `injector()` added
- * to JQuery/jqLite elements. See {@link angular.element}.
- *
- * *This is fairly rare but could be the case if a third party library is injecting the
- * markup.*
- *
- * In the following example a new block of HTML containing a `ng-controller`
- * directive is added to the end of the document body by JQuery. We then compile and link
- * it into the current AngularJS scope.
- *
- *
- *
- * # Injection Function Annotation
- *
- * JavaScript does not have annotations, and annotations are needed for dependency injection. The
- * following are all valid ways of annotating function with injection arguments and are equivalent.
- *
- *
- *
- * ## Inference
- *
- * In JavaScript calling `toString()` on a function returns the function definition. The definition
- * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
- * minification, and obfuscation tools since these tools change the argument names.
- *
- * ## `$inject` Annotation
- * By adding a `$inject` property onto a function the injection parameters can be specified.
- *
- * ## Inline
- * As an array of injection names, where the last item in the array is the function to call.
- */
-
-/**
- * @ngdoc method
- * @name AUTO.$injector#get
- * @methodOf AUTO.$injector
- *
- * @description
- * Return an instance of the service.
- *
- * @param {string} name The name of the instance to retrieve.
- * @return {*} The instance.
- */
-
-/**
- * @ngdoc method
- * @name AUTO.$injector#invoke
- * @methodOf AUTO.$injector
- *
- * @description
- * Invoke the method and supply the method arguments from the `$injector`.
- *
- * @param {!function} fn The function to invoke. Function parameters are injected according to the
- * {@link guide/di $inject Annotation} rules.
- * @param {Object=} self The `this` for the invoked method.
- * @param {Object=} locals Optional object. If preset then any argument names are read from this
- * object first, before the `$injector` is consulted.
- * @returns {*} the value returned by the invoked `fn` function.
- */
-
-/**
- * @ngdoc method
- * @name AUTO.$injector#has
- * @methodOf AUTO.$injector
- *
- * @description
- * Allows the user to query if the particular service exist.
- *
- * @param {string} Name of the service to query.
- * @returns {boolean} returns true if injector has given service.
- */
-
-/**
- * @ngdoc method
- * @name AUTO.$injector#instantiate
- * @methodOf AUTO.$injector
- * @description
- * Create a new instance of JS type. The method takes a constructor function invokes the new
- * operator and supplies all of the arguments to the constructor function as specified by the
- * constructor annotation.
- *
- * @param {function} Type Annotated constructor function.
- * @param {Object=} locals Optional object. If preset then any argument names are read from this
- * object first, before the `$injector` is consulted.
- * @returns {Object} new instance of `Type`.
- */
-
-/**
- * @ngdoc method
- * @name AUTO.$injector#annotate
- * @methodOf AUTO.$injector
- *
- * @description
- * Returns an array of service names which the function is requesting for injection. This API is
- * used by the injector to determine which services need to be injected into the function when the
- * function is invoked. There are three ways in which the function can be annotated with the needed
- * dependencies.
- *
- * # Argument names
- *
- * The simplest form is to extract the dependencies from the arguments of the function. This is done
- * by converting the function into a string using `toString()` method and extracting the argument
- * names.
- *
- * // Given
- * function MyController($scope, $route) {
- * // ...
- * }
- *
- * // Then
- * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
- *
- *
- * This method does not work with code minification / obfuscation. For this reason the following
- * annotation strategies are supported.
- *
- * # The `$inject` property
- *
- * If a function has an `$inject` property and its value is an array of strings, then the strings
- * represent names of services to be injected into the function.
- *
- *
- * # The array notation
- *
- * It is often desirable to inline Injected functions and that's when setting the `$inject` property
- * is very inconvenient. In these situations using the array notation to specify the dependencies in
- * a way that survives minification is a better choice:
- *
- *
- * // We wish to write this (not minification / obfuscation safe)
- * injector.invoke(function($compile, $rootScope) {
- * // ...
- * });
- *
- * // We are forced to write break inlining
- * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
- * // ...
- * };
- * tmpFn.$inject = ['$compile', '$rootScope'];
- * injector.invoke(tmpFn);
- *
- * // To better support inline function the inline annotation is supported
- * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
- * // ...
- * }]);
- *
- * // Therefore
- * expect(injector.annotate(
- * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
- * ).toEqual(['$compile', '$rootScope']);
- *
- *
- * @param {function|Array.} fn Function for which dependent service names need to
- * be retrieved as described above.
- *
- * @returns {Array.} The names of the services which the function requires.
- */
-
-
-
-
-/**
- * @ngdoc object
- * @name AUTO.$provide
- *
- * @description
- *
- * The {@link AUTO.$provide $provide} service has a number of methods for registering components
- * with the {@link AUTO.$injector $injector}. Many of these functions are also exposed on
- * {@link angular.Module}.
- *
- * An Angular **service** is a singleton object created by a **service factory**. These **service
- * factories** are functions which, in turn, are created by a **service provider**.
- * The **service providers** are constructor functions. When instantiated they must contain a
- * property called `$get`, which holds the **service factory** function.
- *
- * When you request a service, the {@link AUTO.$injector $injector} is responsible for finding the
- * correct **service provider**, instantiating it and then calling its `$get` **service factory**
- * function to get the instance of the **service**.
- *
- * Often services have no configuration options and there is no need to add methods to the service
- * provider. The provider will be no more than a constructor function with a `$get` property. For
- * these cases the {@link AUTO.$provide $provide} service has additional helper methods to register
- * services without specifying a provider.
- *
- * * {@link AUTO.$provide#methods_provider provider(provider)} - registers a **service provider** with the
- * {@link AUTO.$injector $injector}
- * * {@link AUTO.$provide#methods_constant constant(obj)} - registers a value/object that can be accessed by
- * providers and services.
- * * {@link AUTO.$provide#methods_value value(obj)} - registers a value/object that can only be accessed by
- * services, not providers.
- * * {@link AUTO.$provide#methods_factory factory(fn)} - registers a service **factory function**, `fn`,
- * that will be wrapped in a **service provider** object, whose `$get` property will contain the
- * given factory function.
- * * {@link AUTO.$provide#methods_service service(class)} - registers a **constructor function**, `class` that
- * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
- * a new object using the given constructor function.
- *
- * See the individual methods for more information and examples.
- */
-
-/**
- * @ngdoc method
- * @name AUTO.$provide#provider
- * @methodOf AUTO.$provide
- * @description
- *
- * Register a **provider function** with the {@link AUTO.$injector $injector}. Provider functions
- * are constructor functions, whose instances are responsible for "providing" a factory for a
- * service.
- *
- * Service provider names start with the name of the service they provide followed by `Provider`.
- * For example, the {@link ng.$log $log} service has a provider called
- * {@link ng.$logProvider $logProvider}.
- *
- * Service provider objects can have additional methods which allow configuration of the provider
- * and its service. Importantly, you can configure what kind of service is created by the `$get`
- * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
- * method {@link ng.$logProvider#debugEnabled debugEnabled}
- * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
- * console or not.
- *
- * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
- 'Provider'` key.
- * @param {(Object|function())} provider If the provider is:
- *
- * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
- * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be
- * created.
- * - `Constructor`: a new instance of the provider will be created using
- * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as
- * `object`.
- *
- * @returns {Object} registered provider instance
-
- * @example
- *
- * The following example shows how to create a simple event tracking service and register it using
- * {@link AUTO.$provide#methods_provider $provide.provider()}.
- *
- *
- * // Define the eventTracker provider
- * function EventTrackerProvider() {
- * var trackingUrl = '/track';
- *
- * // A provider method for configuring where the tracked events should been saved
- * this.setTrackingUrl = function(url) {
- * trackingUrl = url;
- * };
- *
- * // The service factory function
- * this.$get = ['$http', function($http) {
- * var trackedEvents = {};
- * return {
- * // Call this to track an event
- * event: function(event) {
- * var count = trackedEvents[event] || 0;
- * count += 1;
- * trackedEvents[event] = count;
- * return count;
- * },
- * // Call this to save the tracked events to the trackingUrl
- * save: function() {
- * $http.post(trackingUrl, trackedEvents);
- * }
- * };
- * }];
- * }
- *
- * describe('eventTracker', function() {
- * var postSpy;
- *
- * beforeEach(module(function($provide) {
- * // Register the eventTracker provider
- * $provide.provider('eventTracker', EventTrackerProvider);
- * }));
- *
- * beforeEach(module(function(eventTrackerProvider) {
- * // Configure eventTracker provider
- * eventTrackerProvider.setTrackingUrl('/custom-track');
- * }));
- *
- * it('tracks events', inject(function(eventTracker) {
- * expect(eventTracker.event('login')).toEqual(1);
- * expect(eventTracker.event('login')).toEqual(2);
- * }));
- *
- * it('saves to the tracking url', inject(function(eventTracker, $http) {
- * postSpy = spyOn($http, 'post');
- * eventTracker.event('login');
- * eventTracker.save();
- * expect(postSpy).toHaveBeenCalled();
- * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
- * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
- * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
- * }));
- * });
- *
- */
-
-/**
- * @ngdoc method
- * @name AUTO.$provide#factory
- * @methodOf AUTO.$provide
- * @description
- *
- * Register a **service factory**, which will be called to return the service instance.
- * This is short for registering a service where its provider consists of only a `$get` property,
- * which is the given service factory function.
- * You should use {@link AUTO.$provide#factory $provide.factory(getFn)} if you do not need to
- * configure your service in a provider.
- *
- * @param {string} name The name of the instance.
- * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
- * for `$provide.provider(name, {$get: $getFn})`.
- * @returns {Object} registered provider instance
- *
- * @example
- * Here is an example of registering a service
- *
- */
-
-
-/**
- * @ngdoc method
- * @name AUTO.$provide#service
- * @methodOf AUTO.$provide
- * @description
- *
- * Register a **service constructor**, which will be invoked with `new` to create the service
- * instance.
- * This is short for registering a service where its provider's `$get` property is the service
- * constructor function that will be used to instantiate the service instance.
- *
- * You should use {@link AUTO.$provide#methods_service $provide.service(class)} if you define your service
- * as a type/class.
- *
- * @param {string} name The name of the instance.
- * @param {Function} constructor A class (constructor function) that will be instantiated.
- * @returns {Object} registered provider instance
- *
- * @example
- * Here is an example of registering a service using
- * {@link AUTO.$provide#methods_service $provide.service(class)}.
- *
- */
-
-
-/**
- * @ngdoc method
- * @name AUTO.$provide#value
- * @methodOf AUTO.$provide
- * @description
- *
- * Register a **value service** with the {@link AUTO.$injector $injector}, such as a string, a
- * number, an array, an object or a function. This is short for registering a service where its
- * provider's `$get` property is a factory function that takes no arguments and returns the **value
- * service**.
- *
- * Value services are similar to constant services, except that they cannot be injected into a
- * module configuration function (see {@link angular.Module#config}) but they can be overridden by
- * an Angular
- * {@link AUTO.$provide#decorator decorator}.
- *
- * @param {string} name The name of the instance.
- * @param {*} value The value.
- * @returns {Object} registered provider instance
- *
- * @example
- * Here are some examples of creating value services.
- *
- */
-
-
-/**
- * @ngdoc method
- * @name AUTO.$provide#constant
- * @methodOf AUTO.$provide
- * @description
- *
- * Register a **constant service**, such as a string, a number, an array, an object or a function,
- * with the {@link AUTO.$injector $injector}. Unlike {@link AUTO.$provide#value value} it can be
- * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
- * be overridden by an Angular {@link AUTO.$provide#decorator decorator}.
- *
- * @param {string} name The name of the constant.
- * @param {*} value The constant value.
- * @returns {Object} registered instance
- *
- * @example
- * Here a some examples of creating constants:
- *
- */
-
-
-/**
- * @ngdoc method
- * @name AUTO.$provide#decorator
- * @methodOf AUTO.$provide
- * @description
- *
- * Register a **service decorator** with the {@link AUTO.$injector $injector}. A service decorator
- * intercepts the creation of a service, allowing it to override or modify the behaviour of the
- * service. The object returned by the decorator may be the original service, or a new service
- * object which replaces or wraps and delegates to the original service.
- *
- * @param {string} name The name of the service to decorate.
- * @param {function()} decorator This function will be invoked when the service needs to be
- * instantiated and should return the decorated service instance. The function is called using
- * the {@link AUTO.$injector#invoke injector.invoke} method and is therefore fully injectable.
- * Local injection arguments:
- *
- * * `$delegate` - The original service instance, which can be monkey patched, configured,
- * decorated or delegated to.
- *
- * @example
- * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
- * calls to {@link ng.$log#error $log.warn()}.
- *
-
-
- function ScrollCtrl($scope, $location, $anchorScroll) {
- $scope.gotoBottom = function (){
- // set the location.hash to the id of
- // the element you wish to scroll to.
- $location.hash('bottom');
-
- // call $anchorScroll()
- $anchorScroll();
- }
- }
-
-
- #scrollArea {
- height: 350px;
- overflow: auto;
- }
-
- #bottom {
- display: block;
- margin-top: 2000px;
- }
-
-
- */
-function $AnchorScrollProvider() {
-
- var autoScrollingEnabled = true;
-
- this.disableAutoScrolling = function() {
- autoScrollingEnabled = false;
- };
-
- this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
- var document = $window.document;
-
- // helper function to get first anchor from a NodeList
- // can't use filter.filter, as it accepts only instances of Array
- // and IE can't convert NodeList to an array using [].slice
- // TODO(vojta): use filter if we change it to accept lists as well
- function getFirstAnchor(list) {
- var result = null;
- forEach(list, function(element) {
- if (!result && lowercase(element.nodeName) === 'a') result = element;
- });
- return result;
- }
-
- function scroll() {
- var hash = $location.hash(), elm;
-
- // empty hash, scroll to the top of the page
- if (!hash) $window.scrollTo(0, 0);
-
- // element with given id
- else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
-
- // first anchor with given name :-D
- else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
-
- // no element and hash == 'top', scroll to the top of the page
- else if (hash === 'top') $window.scrollTo(0, 0);
- }
-
- // does not scroll when user clicks on anchor link that is currently on
- // (no url change, no $location.hash() change), browser native does scroll
- if (autoScrollingEnabled) {
- $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
- function autoScrollWatchAction() {
- $rootScope.$evalAsync(scroll);
- });
- }
-
- return scroll;
- }];
-}
-
-var $animateMinErr = minErr('$animate');
-
-/**
- * @ngdoc object
- * @name ng.$animateProvider
- *
- * @description
- * Default implementation of $animate that doesn't perform any animations, instead just
- * synchronously performs DOM
- * updates and calls done() callbacks.
- *
- * In order to enable animations the ngAnimate module has to be loaded.
- *
- * To see the functional implementation check out src/ngAnimate/animate.js
- */
-var $AnimateProvider = ['$provide', function($provide) {
-
-
- this.$$selectors = {};
-
-
- /**
- * @ngdoc function
- * @name ng.$animateProvider#register
- * @methodOf ng.$animateProvider
- *
- * @description
- * Registers a new injectable animation factory function. The factory function produces the
- * animation object which contains callback functions for each event that is expected to be
- * animated.
- *
- * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
- * must be called once the element animation is complete. If a function is returned then the
- * animation service will use this function to cancel the animation whenever a cancel event is
- * triggered.
- *
- *
- *
- * return {
- * eventFn : function(element, done) {
- * //code to run the animation
- * //once complete, then run done()
- * return function cancellationFunction() {
- * //code to cancel the animation
- * }
- * }
- * }
- *
- *
- * @param {string} name The name of the animation.
- * @param {function} factory The factory function that will be executed to return the animation
- * object.
- */
- this.register = function(name, factory) {
- var key = name + '-animation';
- if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
- "Expecting class selector starting with '.' got '{0}'.", name);
- this.$$selectors[name.substr(1)] = key;
- $provide.factory(key, factory);
- };
-
- /**
- * @ngdoc function
- * @name ng.$animateProvider#classNameFilter
- * @methodOf ng.$animateProvider
- *
- * @description
- * Sets and/or returns the CSS class regular expression that is checked when performing
- * an animation. Upon bootstrap the classNameFilter value is not set at all and will
- * therefore enable $animate to attempt to perform an animation on any element.
- * When setting the classNameFilter value, animations will only be performed on elements
- * that successfully match the filter expression. This in turn can boost performance
- * for low-powered devices as well as applications containing a lot of structural operations.
- * @param {RegExp=} expression The className expression which will be checked against all animations
- * @return {RegExp} The current CSS className expression value. If null then there is no expression value
- */
- this.classNameFilter = function(expression) {
- if(arguments.length === 1) {
- this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
- }
- return this.$$classNameFilter;
- };
-
- this.$get = ['$timeout', function($timeout) {
-
- /**
- *
- * @ngdoc object
- * @name ng.$animate
- * @description The $animate service provides rudimentary DOM manipulation functions to
- * insert, remove and move elements within the DOM, as well as adding and removing classes.
- * This service is the core service used by the ngAnimate $animator service which provides
- * high-level animation hooks for CSS and JavaScript.
- *
- * $animate is available in the AngularJS core, however, the ngAnimate module must be included
- * to enable full out animation support. Otherwise, $animate will only perform simple DOM
- * manipulation operations.
- *
- * To learn more about enabling animation support, click here to visit the {@link ngAnimate
- * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
- * page}.
- */
- return {
-
- /**
- *
- * @ngdoc function
- * @name ng.$animate#enter
- * @methodOf ng.$animate
- * @function
- * @description Inserts the element into the DOM either after the `after` element or within
- * the `parent` element. Once complete, the done() callback will be fired (if provided).
- * @param {jQuery/jqLite element} element the element which will be inserted into the DOM
- * @param {jQuery/jqLite element} parent the parent element which will append the element as
- * a child (if the after element is not present)
- * @param {jQuery/jqLite element} after the sibling element which will append the element
- * after itself
- * @param {function=} done callback function that will be called after the element has been
- * inserted into the DOM
- */
- enter : function(element, parent, after, done) {
- if (after) {
- after.after(element);
- } else {
- if (!parent || !parent[0]) {
- parent = after.parent();
- }
- parent.append(element);
- }
- done && $timeout(done, 0, false);
- },
-
- /**
- *
- * @ngdoc function
- * @name ng.$animate#leave
- * @methodOf ng.$animate
- * @function
- * @description Removes the element from the DOM. Once complete, the done() callback will be
- * fired (if provided).
- * @param {jQuery/jqLite element} element the element which will be removed from the DOM
- * @param {function=} done callback function that will be called after the element has been
- * removed from the DOM
- */
- leave : function(element, done) {
- element.remove();
- done && $timeout(done, 0, false);
- },
-
- /**
- *
- * @ngdoc function
- * @name ng.$animate#move
- * @methodOf ng.$animate
- * @function
- * @description Moves the position of the provided element within the DOM to be placed
- * either after the `after` element or inside of the `parent` element. Once complete, the
- * done() callback will be fired (if provided).
- *
- * @param {jQuery/jqLite element} element the element which will be moved around within the
- * DOM
- * @param {jQuery/jqLite element} parent the parent element where the element will be
- * inserted into (if the after element is not present)
- * @param {jQuery/jqLite element} after the sibling element where the element will be
- * positioned next to
- * @param {function=} done the callback function (if provided) that will be fired after the
- * element has been moved to its new position
- */
- move : function(element, parent, after, done) {
- // Do not remove element before insert. Removing will cause data associated with the
- // element to be dropped. Insert will implicitly do the remove.
- this.enter(element, parent, after, done);
- },
-
- /**
- *
- * @ngdoc function
- * @name ng.$animate#addClass
- * @methodOf ng.$animate
- * @function
- * @description Adds the provided className CSS class value to the provided element. Once
- * complete, the done() callback will be fired (if provided).
- * @param {jQuery/jqLite element} element the element which will have the className value
- * added to it
- * @param {string} className the CSS class which will be added to the element
- * @param {function=} done the callback function (if provided) that will be fired after the
- * className value has been added to the element
- */
- addClass : function(element, className, done) {
- className = isString(className) ?
- className :
- isArray(className) ? className.join(' ') : '';
- forEach(element, function (element) {
- jqLiteAddClass(element, className);
- });
- done && $timeout(done, 0, false);
- },
-
- /**
- *
- * @ngdoc function
- * @name ng.$animate#removeClass
- * @methodOf ng.$animate
- * @function
- * @description Removes the provided className CSS class value from the provided element.
- * Once complete, the done() callback will be fired (if provided).
- * @param {jQuery/jqLite element} element the element which will have the className value
- * removed from it
- * @param {string} className the CSS class which will be removed from the element
- * @param {function=} done the callback function (if provided) that will be fired after the
- * className value has been removed from the element
- */
- removeClass : function(element, className, done) {
- className = isString(className) ?
- className :
- isArray(className) ? className.join(' ') : '';
- forEach(element, function (element) {
- jqLiteRemoveClass(element, className);
- });
- done && $timeout(done, 0, false);
- },
-
- enabled : noop
- };
- }];
-}];
-
-/**
- * ! This is a private undocumented service !
- *
- * @name ng.$browser
- * @requires $log
- * @description
- * This object has two goals:
- *
- * - hide all the global state in the browser caused by the window object
- * - abstract away all the browser specific features and inconsistencies
- *
- * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
- * service, which can be used for convenient testing of the application without the interaction with
- * the real browser apis.
- */
-/**
- * @param {object} window The global window object.
- * @param {object} document jQuery wrapped document.
- * @param {function()} XHR XMLHttpRequest constructor.
- * @param {object} $log console.log or an object with the same interface.
- * @param {object} $sniffer $sniffer service
- */
-function Browser(window, document, $log, $sniffer) {
- var self = this,
- rawDocument = document[0],
- location = window.location,
- history = window.history,
- setTimeout = window.setTimeout,
- clearTimeout = window.clearTimeout,
- pendingDeferIds = {};
-
- self.isMock = false;
-
- var outstandingRequestCount = 0;
- var outstandingRequestCallbacks = [];
-
- // TODO(vojta): remove this temporary api
- self.$$completeOutstandingRequest = completeOutstandingRequest;
- self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
-
- /**
- * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
- * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
- */
- function completeOutstandingRequest(fn) {
- try {
- fn.apply(null, sliceArgs(arguments, 1));
- } finally {
- outstandingRequestCount--;
- if (outstandingRequestCount === 0) {
- while(outstandingRequestCallbacks.length) {
- try {
- outstandingRequestCallbacks.pop()();
- } catch (e) {
- $log.error(e);
- }
- }
- }
- }
- }
-
- /**
- * @private
- * Note: this method is used only by scenario runner
- * TODO(vojta): prefix this method with $$ ?
- * @param {function()} callback Function that will be called when no outstanding request
- */
- self.notifyWhenNoOutstandingRequests = function(callback) {
- // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
- // at some deterministic time in respect to the test runner's actions. Leaving things up to the
- // regular poller would result in flaky tests.
- forEach(pollFns, function(pollFn){ pollFn(); });
-
- if (outstandingRequestCount === 0) {
- callback();
- } else {
- outstandingRequestCallbacks.push(callback);
- }
- };
-
- //////////////////////////////////////////////////////////////
- // Poll Watcher API
- //////////////////////////////////////////////////////////////
- var pollFns = [],
- pollTimeout;
-
- /**
- * @name ng.$browser#addPollFn
- * @methodOf ng.$browser
- *
- * @param {function()} fn Poll function to add
- *
- * @description
- * Adds a function to the list of functions that poller periodically executes,
- * and starts polling if not started yet.
- *
- * @returns {function()} the added function
- */
- self.addPollFn = function(fn) {
- if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
- pollFns.push(fn);
- return fn;
- };
-
- /**
- * @param {number} interval How often should browser call poll functions (ms)
- * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
- *
- * @description
- * Configures the poller to run in the specified intervals, using the specified
- * setTimeout fn and kicks it off.
- */
- function startPoller(interval, setTimeout) {
- (function check() {
- forEach(pollFns, function(pollFn){ pollFn(); });
- pollTimeout = setTimeout(check, interval);
- })();
- }
-
- //////////////////////////////////////////////////////////////
- // URL API
- //////////////////////////////////////////////////////////////
-
- var lastBrowserUrl = location.href,
- baseElement = document.find('base'),
- newLocation = null;
-
- /**
- * @name ng.$browser#url
- * @methodOf ng.$browser
- *
- * @description
- * GETTER:
- * Without any argument, this method just returns current value of location.href.
- *
- * SETTER:
- * With at least one argument, this method sets url to new value.
- * If html5 history api supported, pushState/replaceState is used, otherwise
- * location.href/location.replace is used.
- * Returns its own instance to allow chaining
- *
- * NOTE: this api is intended for use only by the $location service. Please use the
- * {@link ng.$location $location service} to change url.
- *
- * @param {string} url New url (when used as setter)
- * @param {boolean=} replace Should new url replace current history record ?
- */
- self.url = function(url, replace) {
- // Android Browser BFCache causes location, history reference to become stale.
- if (location !== window.location) location = window.location;
- if (history !== window.history) history = window.history;
-
- // setter
- if (url) {
- if (lastBrowserUrl == url) return;
- lastBrowserUrl = url;
- if ($sniffer.history) {
- if (replace) history.replaceState(null, '', url);
- else {
- history.pushState(null, '', url);
- // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
- baseElement.attr('href', baseElement.attr('href'));
- }
- } else {
- newLocation = url;
- if (replace) {
- location.replace(url);
- } else {
- location.href = url;
- }
- }
- return self;
- // getter
- } else {
- // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
- // methods not updating location.href synchronously.
- // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
- return newLocation || location.href.replace(/%27/g,"'");
- }
- };
-
- var urlChangeListeners = [],
- urlChangeInit = false;
-
- function fireUrlChange() {
- newLocation = null;
- if (lastBrowserUrl == self.url()) return;
-
- lastBrowserUrl = self.url();
- forEach(urlChangeListeners, function(listener) {
- listener(self.url());
- });
- }
-
- /**
- * @name ng.$browser#onUrlChange
- * @methodOf ng.$browser
- * @TODO(vojta): refactor to use node's syntax for events
- *
- * @description
- * Register callback function that will be called, when url changes.
- *
- * It's only called when the url is changed from outside of angular:
- * - user types different url into address bar
- * - user clicks on history (forward/back) button
- * - user clicks on a link
- *
- * It's not called when url is changed by $browser.url() method
- *
- * The listener gets called with new url as parameter.
- *
- * NOTE: this api is intended for use only by the $location service. Please use the
- * {@link ng.$location $location service} to monitor url changes in angular apps.
- *
- * @param {function(string)} listener Listener function to be called when url changes.
- * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
- */
- self.onUrlChange = function(callback) {
- if (!urlChangeInit) {
- // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
- // don't fire popstate when user change the address bar and don't fire hashchange when url
- // changed by push/replaceState
-
- // html5 history api - popstate event
- if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
- // hashchange event
- if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
- // polling
- else self.addPollFn(fireUrlChange);
-
- urlChangeInit = true;
- }
-
- urlChangeListeners.push(callback);
- return callback;
- };
-
- //////////////////////////////////////////////////////////////
- // Misc API
- //////////////////////////////////////////////////////////////
-
- /**
- * @name ng.$browser#baseHref
- * @methodOf ng.$browser
- *
- * @description
- * Returns current
- * (always relative - without domain)
- *
- * @returns {string=} current
- */
- self.baseHref = function() {
- var href = baseElement.attr('href');
- return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
- };
-
- //////////////////////////////////////////////////////////////
- // Cookies API
- //////////////////////////////////////////////////////////////
- var lastCookies = {};
- var lastCookieString = '';
- var cookiePath = self.baseHref();
-
- /**
- * @name ng.$browser#cookies
- * @methodOf ng.$browser
- *
- * @param {string=} name Cookie name
- * @param {string=} value Cookie value
- *
- * @description
- * The cookies method provides a 'private' low level access to browser cookies.
- * It is not meant to be used directly, use the $cookie service instead.
- *
- * The return values vary depending on the arguments that the method was called with as follows:
- *
- * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
- * it
- * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
- * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
- * way)
- *
- * @returns {Object} Hash of all cookies (if called without any parameter)
- */
- self.cookies = function(name, value) {
- /* global escape: false, unescape: false */
- var cookieLength, cookieArray, cookie, i, index;
-
- if (name) {
- if (value === undefined) {
- rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
- ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
- } else {
- if (isString(value)) {
- cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
- ';path=' + cookiePath).length + 1;
-
- // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
- // - 300 cookies
- // - 20 cookies per unique domain
- // - 4096 bytes per cookie
- if (cookieLength > 4096) {
- $log.warn("Cookie '"+ name +
- "' possibly not set or overflowed because it was too large ("+
- cookieLength + " > 4096 bytes)!");
- }
- }
- }
- } else {
- if (rawDocument.cookie !== lastCookieString) {
- lastCookieString = rawDocument.cookie;
- cookieArray = lastCookieString.split("; ");
- lastCookies = {};
-
- for (i = 0; i < cookieArray.length; i++) {
- cookie = cookieArray[i];
- index = cookie.indexOf('=');
- if (index > 0) { //ignore nameless cookies
- name = unescape(cookie.substring(0, index));
- // the first value that is seen for a cookie is the most
- // specific one. values for the same cookie name that
- // follow are for less specific paths.
- if (lastCookies[name] === undefined) {
- lastCookies[name] = unescape(cookie.substring(index + 1));
- }
- }
- }
- }
- return lastCookies;
- }
- };
-
-
- /**
- * @name ng.$browser#defer
- * @methodOf ng.$browser
- * @param {function()} fn A function, who's execution should be deferred.
- * @param {number=} [delay=0] of milliseconds to defer the function execution.
- * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
- *
- * @description
- * Executes a fn asynchronously via `setTimeout(fn, delay)`.
- *
- * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
- * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
- * via `$browser.defer.flush()`.
- *
- */
- self.defer = function(fn, delay) {
- var timeoutId;
- outstandingRequestCount++;
- timeoutId = setTimeout(function() {
- delete pendingDeferIds[timeoutId];
- completeOutstandingRequest(fn);
- }, delay || 0);
- pendingDeferIds[timeoutId] = true;
- return timeoutId;
- };
-
-
- /**
- * @name ng.$browser#defer.cancel
- * @methodOf ng.$browser.defer
- *
- * @description
- * Cancels a deferred task identified with `deferId`.
- *
- * @param {*} deferId Token returned by the `$browser.defer` function.
- * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
- * canceled.
- */
- self.defer.cancel = function(deferId) {
- if (pendingDeferIds[deferId]) {
- delete pendingDeferIds[deferId];
- clearTimeout(deferId);
- completeOutstandingRequest(noop);
- return true;
- }
- return false;
- };
-
-}
-
-function $BrowserProvider(){
- this.$get = ['$window', '$log', '$sniffer', '$document',
- function( $window, $log, $sniffer, $document){
- return new Browser($window, $document, $log, $sniffer);
- }];
-}
-
-/**
- * @ngdoc object
- * @name ng.$cacheFactory
- *
- * @description
- * Factory that constructs cache objects and gives access to them.
- *
- *
- *
- *
- * @param {string} cacheId Name or id of the newly created cache.
- * @param {object=} options Options object that specifies the cache behavior. Properties:
- *
- * - `{number=}` `capacity` — turns the cache into LRU cache.
- *
- * @returns {object} Newly created cache object with the following set of methods:
- *
- * - `{object}` `info()` — Returns id, size, and options of cache.
- * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
- * it.
- * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
- * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
- * - `{void}` `removeAll()` — Removes all cached values.
- * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
- *
- */
-function $CacheFactoryProvider() {
-
- this.$get = function() {
- var caches = {};
-
- function cacheFactory(cacheId, options) {
- if (cacheId in caches) {
- throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
- }
-
- var size = 0,
- stats = extend({}, options, {id: cacheId}),
- data = {},
- capacity = (options && options.capacity) || Number.MAX_VALUE,
- lruHash = {},
- freshEnd = null,
- staleEnd = null;
-
- return caches[cacheId] = {
-
- put: function(key, value) {
- var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
-
- refresh(lruEntry);
-
- if (isUndefined(value)) return;
- if (!(key in data)) size++;
- data[key] = value;
-
- if (size > capacity) {
- this.remove(staleEnd.key);
- }
-
- return value;
- },
-
-
- get: function(key) {
- var lruEntry = lruHash[key];
-
- if (!lruEntry) return;
-
- refresh(lruEntry);
-
- return data[key];
- },
-
-
- remove: function(key) {
- var lruEntry = lruHash[key];
-
- if (!lruEntry) return;
-
- if (lruEntry == freshEnd) freshEnd = lruEntry.p;
- if (lruEntry == staleEnd) staleEnd = lruEntry.n;
- link(lruEntry.n,lruEntry.p);
-
- delete lruHash[key];
- delete data[key];
- size--;
- },
-
-
- removeAll: function() {
- data = {};
- size = 0;
- lruHash = {};
- freshEnd = staleEnd = null;
- },
-
-
- destroy: function() {
- data = null;
- stats = null;
- lruHash = null;
- delete caches[cacheId];
- },
-
-
- info: function() {
- return extend({}, stats, {size: size});
- }
- };
-
-
- /**
- * makes the `entry` the freshEnd of the LRU linked list
- */
- function refresh(entry) {
- if (entry != freshEnd) {
- if (!staleEnd) {
- staleEnd = entry;
- } else if (staleEnd == entry) {
- staleEnd = entry.n;
- }
-
- link(entry.n, entry.p);
- link(entry, freshEnd);
- freshEnd = entry;
- freshEnd.n = null;
- }
- }
-
-
- /**
- * bidirectionally links two entries of the LRU linked list
- */
- function link(nextEntry, prevEntry) {
- if (nextEntry != prevEntry) {
- if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
- if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
- }
- }
- }
-
-
- /**
- * @ngdoc method
- * @name ng.$cacheFactory#info
- * @methodOf ng.$cacheFactory
- *
- * @description
- * Get information about all the of the caches that have been created
- *
- * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
- */
- cacheFactory.info = function() {
- var info = {};
- forEach(caches, function(cache, cacheId) {
- info[cacheId] = cache.info();
- });
- return info;
- };
-
-
- /**
- * @ngdoc method
- * @name ng.$cacheFactory#get
- * @methodOf ng.$cacheFactory
- *
- * @description
- * Get access to a cache object by the `cacheId` used when it was created.
- *
- * @param {string} cacheId Name or id of a cache to access.
- * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
- */
- cacheFactory.get = function(cacheId) {
- return caches[cacheId];
- };
-
-
- return cacheFactory;
- };
-}
-
-/**
- * @ngdoc object
- * @name ng.$templateCache
- *
- * @description
- * The first time a template is used, it is loaded in the template cache for quick retrieval. You
- * can load templates directly into the cache in a `script` tag, or by consuming the
- * `$templateCache` service directly.
- *
- * Adding via the `script` tag:
- *
- *
- *
- *
- *
- * ...
- *
- *
- *
- * **Note:** the `script` tag containing the template does not need to be included in the `head` of
- * the document, but it must be below the `ng-app` definition.
- *
- * Adding via the $templateCache service:
- *
- *
- * var myApp = angular.module('myApp', []);
- * myApp.run(function($templateCache) {
- * $templateCache.put('templateId.html', 'This is the content of the template');
- * });
- *
- *
- * To retrieve the template later, simply use it in your HTML:
- *
- *
- *
- *
- * or get it via Javascript:
- *
- * $templateCache.get('templateId.html')
- *
- *
- * See {@link ng.$cacheFactory $cacheFactory}.
- *
- */
-function $TemplateCacheProvider() {
- this.$get = ['$cacheFactory', function($cacheFactory) {
- return $cacheFactory('templates');
- }];
-}
-
-/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
- *
- * DOM-related variables:
- *
- * - "node" - DOM Node
- * - "element" - DOM Element or Node
- * - "$node" or "$element" - jqLite-wrapped node or element
- *
- *
- * Compiler related stuff:
- *
- * - "linkFn" - linking fn of a single directive
- * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
- * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
- * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
- */
-
-
-/**
- * @ngdoc function
- * @name ng.$compile
- * @function
- *
- * @description
- * Compiles an HTML string or DOM into a template and produces a template function, which
- * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
- *
- * The compilation is a process of walking the DOM tree and matching DOM elements to
- * {@link ng.$compileProvider#methods_directive directives}.
- *
- *
- * **Note:** This document is an in-depth reference of all directive options.
- * For a gentle introduction to directives with examples of common use cases,
- * see the {@link guide/directive directive guide}.
- *
- *
- * ## Comprehensive Directive API
- *
- * There are many different options for a directive.
- *
- * The difference resides in the return value of the factory function.
- * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
- * or just the `postLink` function (all other properties will have the default values).
- *
- *
- * **Best Practice:** It's recommended to use the "directive definition object" form.
- *
- *
- * Here's an example directive declared with a Directive Definition Object:
- *
- *
- * **Note:** Any unspecified options will use the default value. You can see the default values below.
- *
- *
- * Therefore the above can be simplified as:
- *
- *
- * var myModule = angular.module(...);
- *
- * myModule.directive('directiveName', function factory(injectables) {
- * var directiveDefinitionObject = {
- * link: function postLink(scope, iElement, iAttrs) { ... }
- * };
- * return directiveDefinitionObject;
- * // or
- * // return function postLink(scope, iElement, iAttrs) { ... }
- * });
- *
- *
- *
- *
- * ### Directive Definition Object
- *
- * The directive definition object provides instructions to the {@link api/ng.$compile
- * compiler}. The attributes are:
- *
- * #### `priority`
- * When there are multiple directives defined on a single DOM element, sometimes it
- * is necessary to specify the order in which the directives are applied. The `priority` is used
- * to sort the directives before their `compile` functions get called. Priority is defined as a
- * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
- * are also run in priority order, but post-link functions are run in reverse order. The order
- * of directives with the same priority is undefined. The default priority is `0`.
- *
- * #### `terminal`
- * If set to true then the current `priority` will be the last set of directives
- * which will execute (any directives at the current priority will still execute
- * as the order of execution on same `priority` is undefined).
- *
- * #### `scope`
- * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
- * same element request a new scope, only one new scope is created. The new scope rule does not
- * apply for the root of the template since the root of the template always gets a new scope.
- *
- * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
- * normal scope in that it does not prototypically inherit from the parent scope. This is useful
- * when creating reusable components, which should not accidentally read or modify data in the
- * parent scope.
- *
- * The 'isolate' scope takes an object hash which defines a set of local scope properties
- * derived from the parent scope. These local properties are useful for aliasing values for
- * templates. Locals definition is a hash of local scope property to its source:
- *
- * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
- * always a string since DOM attributes are strings. If no `attr` name is specified then the
- * attribute name is assumed to be the same as the local name.
- * Given `` and widget definition
- * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
- * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
- * `localName` property on the widget scope. The `name` is read from the parent scope (not
- * component scope).
- *
- * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
- * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
- * name is specified then the attribute name is assumed to be the same as the local name.
- * Given `` and widget definition of
- * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
- * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
- * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
- * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
- * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
- *
- * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
- * If no `attr` name is specified then the attribute name is assumed to be the same as the
- * local name. Given `` and widget definition of
- * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
- * a function wrapper for the `count = count + value` expression. Often it's desirable to
- * pass data from the isolated scope via an expression and to the parent scope, this can be
- * done by passing a map of local variable names and values into the expression wrapper fn.
- * For example, if the expression is `increment(amount)` then we can specify the amount value
- * by calling the `localFn` as `localFn({amount: 22})`.
- *
- *
- *
- * #### `controller`
- * Controller constructor function. The controller is instantiated before the
- * pre-linking phase and it is shared with other directives (see
- * `require` attribute). This allows the directives to communicate with each other and augment
- * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
- *
- * * `$scope` - Current scope associated with the element
- * * `$element` - Current element
- * * `$attrs` - Current attributes object for the element
- * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
- * The scope can be overridden by an optional first argument.
- * `function([scope], cloneLinkingFn)`.
- *
- *
- * #### `require`
- * Require another directive and inject its controller as the fourth argument to the linking function. The
- * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
- * injected argument will be an array in corresponding order. If no such directive can be
- * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
- *
- * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
- * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
- * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
- * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
- * `link` fn if not found.
- *
- *
- * #### `controllerAs`
- * Controller alias at the directive scope. An alias for the controller so it
- * can be referenced at the directive template. The directive needs to define a scope for this
- * configuration to be used. Useful in the case when directive is used as component.
- *
- *
- * #### `restrict`
- * String of subset of `EACM` which restricts the directive to a specific directive
- * declaration style. If omitted, the default (attributes only) is used.
- *
- * * `E` - Element name: ``
- * * `A` - Attribute (default): ``
- * * `C` - Class: ``
- * * `M` - Comment: ``
- *
- *
- * #### `template`
- * replace the current element with the contents of the HTML. The replacement process
- * migrates all of the attributes / classes from the old element to the new one. See the
- * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
- * Directives Guide} for an example.
- *
- * You can specify `template` as a string representing the template or as a function which takes
- * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
- * returns a string value representing the template.
- *
- *
- * #### `templateUrl`
- * Same as `template` but the template is loaded from the specified URL. Because
- * the template loading is asynchronous the compilation/linking is suspended until the template
- * is loaded.
- *
- * You can specify `templateUrl` as a string representing the URL or as a function which takes two
- * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
- * a string value representing the url. In either case, the template URL is passed through {@link
- * api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}.
- *
- *
- * #### `replace`
- * specify where the template should be inserted. Defaults to `false`.
- *
- * * `true` - the template will replace the current element.
- * * `false` - the template will replace the contents of the current element.
- *
- *
- * #### `transclude`
- * compile the content of the element and make it available to the directive.
- * Typically used with {@link api/ng.directive:ngTransclude
- * ngTransclude}. The advantage of transclusion is that the linking function receives a
- * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
- * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
- * scope. This makes it possible for the widget to have private state, and the transclusion to
- * be bound to the parent (pre-`isolate`) scope.
- *
- * * `true` - transclude the content of the directive.
- * * `'element'` - transclude the whole element including any directives defined at lower priority.
- *
- *
- * #### `compile`
- *
- *
- *
- * The compile function deals with transforming the template DOM. Since most directives do not do
- * template transformation, it is not used often. Examples that require compile functions are
- * directives that transform template DOM, such as {@link
- * api/ng.directive:ngRepeat ngRepeat}, or load the contents
- * asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The
- * compile function takes the following arguments.
- *
- * * `tElement` - template element - The element where the directive has been declared. It is
- * safe to do template transformation on the element and child elements only.
- *
- * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
- * between all directive compile functions.
- *
- * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
- *
- *
- * **Note:** The template instance and the link instance may be different objects if the template has
- * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
- * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
- * should be done in a linking function rather than in a compile function.
- *
- *
- *
- * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
- * e.g. does not know about the right outer scope. Please use the transclude function that is passed
- * to the link function instead.
- *
-
- * A compile function can have a return value which can be either a function or an object.
- *
- * * returning a (post-link) function - is equivalent to registering the linking function via the
- * `link` property of the config object when the compile function is empty.
- *
- * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
- * control when a linking function should be called during the linking phase. See info about
- * pre-linking and post-linking functions below.
- *
- *
- * #### `link`
- * This property is used only if the `compile` property is not defined.
- *
- *
- *
- * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
- * executed after the template has been cloned. This is where most of the directive logic will be
- * put.
- *
- * * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
- * directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}.
- *
- * * `iElement` - instance element - The element where the directive is to be used. It is safe to
- * manipulate the children of the element only in `postLink` function since the children have
- * already been linked.
- *
- * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
- * between all directive linking functions.
- *
- * * `controller` - a controller instance - A controller instance if at least one directive on the
- * element defines a controller. The controller is shared among all the directives, which allows
- * the directives to use the controllers as a communication channel.
- *
- * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
- * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
- * parameter of directive controllers.
- * `function([scope], cloneLinkingFn)`.
- *
- *
- * #### Pre-linking function
- *
- * Executed before the child elements are linked. Not safe to do DOM transformation since the
- * compiler linking function will fail to locate the correct elements for linking.
- *
- * #### Post-linking function
- *
- * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
- *
- *
- * ### Attributes
- *
- * The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
- * `link()` or `compile()` functions. It has a variety of uses.
- *
- * accessing *Normalized attribute names:*
- * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
- * the attributes object allows for normalized access to
- * the attributes.
- *
- * * *Directive inter-communication:* All directives share the same instance of the attributes
- * object which allows the directives to use the attributes object as inter directive
- * communication.
- *
- * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
- * allowing other directives to read the interpolated value.
- *
- * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
- * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
- * the only way to easily get the actual value because during the linking phase the interpolation
- * hasn't been evaluated yet and so the value is at this time set to `undefined`.
- *
- *
- * function linkingFn(scope, elm, attrs, ctrl) {
- * // get the attribute value
- * console.log(attrs.ngModel);
- *
- * // change the attribute
- * attrs.$set('ngModel', 'new value');
- *
- * // observe changes to interpolated attribute
- * attrs.$observe('ngModel', function(value) {
- * console.log('ngModel has changed value to ' + value);
- * });
- * }
- *
- *
- * Below is an example using `$compileProvider`.
- *
- *
- * **Note**: Typically directives are registered with `module.directive`. The example below is
- * to illustrate how `$compile` works.
- *
- *
-
-
-
-
-
-
-
-
-
-
- it('should auto compile', function() {
- expect(element('div[compile]').text()).toBe('Hello Angular');
- input('html').enter('{{name}}!');
- expect(element('div[compile]').text()).toBe('Angular!');
- });
-
-
-
- *
- *
- * @param {string|DOMElement} element Element or HTML string to compile into a template function.
- * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
- * @param {number} maxPriority only apply directives lower then given priority (Only effects the
- * root element(s), not their children)
- * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
- * (a DOM element/tree) to a scope. Where:
- *
- * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
- * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
- * `template` and call the `cloneAttachFn` function allowing the caller to attach the
- * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
- * called as: `cloneAttachFn(clonedElement, scope)` where:
- *
- * * `clonedElement` - is a clone of the original `element` passed into the compiler.
- * * `scope` - is the current scope with which the linking function is working with.
- *
- * Calling the linking function returns the element of the template. It is either the original
- * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
- *
- * After linking the view is not updated until after a call to $digest which typically is done by
- * Angular automatically.
- *
- * If you need access to the bound view, there are two ways to do it:
- *
- * - If you are not asking the linking function to clone the template, create the DOM element(s)
- * before you send them to the compiler and keep this reference around.
- *
- * var element = $compile('
{{total}}
')(scope);
- *
- *
- * - if on the other hand, you need the element to be cloned, the view reference from the original
- * example would not point to the clone, but rather to the original template that was cloned. In
- * this case, you can access the clone via the cloneAttachFn:
- *
- * var templateElement = angular.element('
{{total}}
'),
- * scope = ....;
- *
- * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
- * //attach the clone to DOM document at the right place
- * });
- *
- * //now we have reference to the cloned DOM via `clonedElement`
- *
- *
- *
- * For information on how the compiler works, see the
- * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
- */
-
-var $compileMinErr = minErr('$compile');
-
-/**
- * @ngdoc service
- * @name ng.$compileProvider
- * @function
- *
- * @description
- */
-$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
-function $CompileProvider($provide, $$sanitizeUriProvider) {
- var hasDirectives = {},
- Suffix = 'Directive',
- COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
- CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;
-
- // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
- // The assumption is that future DOM event attribute names will begin with
- // 'on' and be composed of only English letters.
- var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
-
- /**
- * @ngdoc function
- * @name ng.$compileProvider#directive
- * @methodOf ng.$compileProvider
- * @function
- *
- * @description
- * Register a new directive with the compiler.
- *
- * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which
- * will match as ng-bind), or an object map of directives where the keys are the
- * names and the values are the factories.
- * @param {function|Array} directiveFactory An injectable directive factory function. See
- * {@link guide/directive} for more info.
- * @returns {ng.$compileProvider} Self for chaining.
- */
- this.directive = function registerDirective(name, directiveFactory) {
- assertNotHasOwnProperty(name, 'directive');
- if (isString(name)) {
- assertArg(directiveFactory, 'directiveFactory');
- if (!hasDirectives.hasOwnProperty(name)) {
- hasDirectives[name] = [];
- $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
- function($injector, $exceptionHandler) {
- var directives = [];
- forEach(hasDirectives[name], function(directiveFactory, index) {
- try {
- var directive = $injector.invoke(directiveFactory);
- if (isFunction(directive)) {
- directive = { compile: valueFn(directive) };
- } else if (!directive.compile && directive.link) {
- directive.compile = valueFn(directive.link);
- }
- directive.priority = directive.priority || 0;
- directive.index = index;
- directive.name = directive.name || name;
- directive.require = directive.require || (directive.controller && directive.name);
- directive.restrict = directive.restrict || 'A';
- directives.push(directive);
- } catch (e) {
- $exceptionHandler(e);
- }
- });
- return directives;
- }]);
- }
- hasDirectives[name].push(directiveFactory);
- } else {
- forEach(name, reverseParams(registerDirective));
- }
- return this;
- };
-
-
- /**
- * @ngdoc function
- * @name ng.$compileProvider#aHrefSanitizationWhitelist
- * @methodOf ng.$compileProvider
- * @function
- *
- * @description
- * Retrieves or overrides the default regular expression that is used for whitelisting of safe
- * urls during a[href] sanitization.
- *
- * The sanitization is a security measure aimed at prevent XSS attacks via html links.
- *
- * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
- * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
- * regular expression. If a match is found, the original url is written into the dom. Otherwise,
- * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
- *
- * @param {RegExp=} regexp New regexp to whitelist urls with.
- * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
- * chaining otherwise.
- */
- this.aHrefSanitizationWhitelist = function(regexp) {
- if (isDefined(regexp)) {
- $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
- return this;
- } else {
- return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
- }
- };
-
-
- /**
- * @ngdoc function
- * @name ng.$compileProvider#imgSrcSanitizationWhitelist
- * @methodOf ng.$compileProvider
- * @function
- *
- * @description
- * Retrieves or overrides the default regular expression that is used for whitelisting of safe
- * urls during img[src] sanitization.
- *
- * The sanitization is a security measure aimed at prevent XSS attacks via html links.
- *
- * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
- * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
- * regular expression. If a match is found, the original url is written into the dom. Otherwise,
- * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
- *
- * @param {RegExp=} regexp New regexp to whitelist urls with.
- * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
- * chaining otherwise.
- */
- this.imgSrcSanitizationWhitelist = function(regexp) {
- if (isDefined(regexp)) {
- $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
- return this;
- } else {
- return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
- }
- };
-
- this.$get = [
- '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
- '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
- function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
- $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
-
- var Attributes = function(element, attr) {
- this.$$element = element;
- this.$attr = attr || {};
- };
-
- Attributes.prototype = {
- $normalize: directiveNormalize,
-
-
- /**
- * @ngdoc function
- * @name ng.$compile.directive.Attributes#$addClass
- * @methodOf ng.$compile.directive.Attributes
- * @function
- *
- * @description
- * Adds the CSS class value specified by the classVal parameter to the element. If animations
- * are enabled then an animation will be triggered for the class addition.
- *
- * @param {string} classVal The className value that will be added to the element
- */
- $addClass : function(classVal) {
- if(classVal && classVal.length > 0) {
- $animate.addClass(this.$$element, classVal);
- }
- },
-
- /**
- * @ngdoc function
- * @name ng.$compile.directive.Attributes#$removeClass
- * @methodOf ng.$compile.directive.Attributes
- * @function
- *
- * @description
- * Removes the CSS class value specified by the classVal parameter from the element. If
- * animations are enabled then an animation will be triggered for the class removal.
- *
- * @param {string} classVal The className value that will be removed from the element
- */
- $removeClass : function(classVal) {
- if(classVal && classVal.length > 0) {
- $animate.removeClass(this.$$element, classVal);
- }
- },
-
- /**
- * @ngdoc function
- * @name ng.$compile.directive.Attributes#$updateClass
- * @methodOf ng.$compile.directive.Attributes
- * @function
- *
- * @description
- * Adds and removes the appropriate CSS class values to the element based on the difference
- * between the new and old CSS class values (specified as newClasses and oldClasses).
- *
- * @param {string} newClasses The current CSS className value
- * @param {string} oldClasses The former CSS className value
- */
- $updateClass : function(newClasses, oldClasses) {
- this.$removeClass(tokenDifference(oldClasses, newClasses));
- this.$addClass(tokenDifference(newClasses, oldClasses));
- },
-
- /**
- * Set a normalized attribute on the element in a way such that all directives
- * can share the attribute. This function properly handles boolean attributes.
- * @param {string} key Normalized key. (ie ngAttribute)
- * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
- * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
- * Defaults to true.
- * @param {string=} attrName Optional none normalized name. Defaults to key.
- */
- $set: function(key, value, writeAttr, attrName) {
- // TODO: decide whether or not to throw an error if "class"
- //is set through this function since it may cause $updateClass to
- //become unstable.
-
- var booleanKey = getBooleanAttrName(this.$$element[0], key),
- normalizedVal,
- nodeName;
-
- if (booleanKey) {
- this.$$element.prop(key, value);
- attrName = booleanKey;
- }
-
- this[key] = value;
-
- // translate normalized key to actual key
- if (attrName) {
- this.$attr[key] = attrName;
- } else {
- attrName = this.$attr[key];
- if (!attrName) {
- this.$attr[key] = attrName = snake_case(key, '-');
- }
- }
-
- nodeName = nodeName_(this.$$element);
-
- // sanitize a[href] and img[src] values
- if ((nodeName === 'A' && key === 'href') ||
- (nodeName === 'IMG' && key === 'src')) {
- this[key] = value = $$sanitizeUri(value, key === 'src');
- }
-
- if (writeAttr !== false) {
- if (value === null || value === undefined) {
- this.$$element.removeAttr(attrName);
- } else {
- this.$$element.attr(attrName, value);
- }
- }
-
- // fire observers
- var $$observers = this.$$observers;
- $$observers && forEach($$observers[key], function(fn) {
- try {
- fn(value);
- } catch (e) {
- $exceptionHandler(e);
- }
- });
- },
-
-
- /**
- * @ngdoc function
- * @name ng.$compile.directive.Attributes#$observe
- * @methodOf ng.$compile.directive.Attributes
- * @function
- *
- * @description
- * Observes an interpolated attribute.
- *
- * The observer function will be invoked once during the next `$digest` following
- * compilation. The observer is then invoked whenever the interpolated value
- * changes.
- *
- * @param {string} key Normalized key. (ie ngAttribute) .
- * @param {function(interpolatedValue)} fn Function that will be called whenever
- the interpolated value of the attribute changes.
- * See the {@link guide/directive#Attributes Directives} guide for more info.
- * @returns {function()} the `fn` parameter.
- */
- $observe: function(key, fn) {
- var attrs = this,
- $$observers = (attrs.$$observers || (attrs.$$observers = {})),
- listeners = ($$observers[key] || ($$observers[key] = []));
-
- listeners.push(fn);
- $rootScope.$evalAsync(function() {
- if (!listeners.$$inter) {
- // no one registered attribute interpolation function, so lets call it manually
- fn(attrs[key]);
- }
- });
- return fn;
- }
- };
-
- var startSymbol = $interpolate.startSymbol(),
- endSymbol = $interpolate.endSymbol(),
- denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
- ? identity
- : function denormalizeTemplate(template) {
- return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
- },
- NG_ATTR_BINDING = /^ngAttr[A-Z]/;
-
-
- return compile;
-
- //================================
-
- function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
- previousCompileContext) {
- if (!($compileNodes instanceof jqLite)) {
- // jquery always rewraps, whereas we need to preserve the original selector so that we can
- // modify it.
- $compileNodes = jqLite($compileNodes);
- }
- // We can not compile top level text elements since text nodes can be merged and we will
- // not be able to attach scope data to them, so we will wrap them in
- forEach($compileNodes, function(node, index){
- if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
- $compileNodes[index] = node = jqLite(node).wrap('').parent()[0];
- }
- });
- var compositeLinkFn =
- compileNodes($compileNodes, transcludeFn, $compileNodes,
- maxPriority, ignoreDirective, previousCompileContext);
- safeAddClass($compileNodes, 'ng-scope');
- return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){
- assertArg(scope, 'scope');
- // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
- // and sometimes changes the structure of the DOM.
- var $linkNode = cloneConnectFn
- ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
- : $compileNodes;
-
- forEach(transcludeControllers, function(instance, name) {
- $linkNode.data('$' + name + 'Controller', instance);
- });
-
- // Attach scope only to non-text nodes.
- for(var i = 0, ii = $linkNode.length; i
- addDirective(directives,
- directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
-
- // iterate over the attributes
- for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
- j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
- var attrStartName = false;
- var attrEndName = false;
-
- attr = nAttrs[j];
- if (!msie || msie >= 8 || attr.specified) {
- name = attr.name;
- // support ngAttr attribute binding
- ngAttrName = directiveNormalize(name);
- if (NG_ATTR_BINDING.test(ngAttrName)) {
- name = snake_case(ngAttrName.substr(6), '-');
- }
-
- var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
- if (ngAttrName === directiveNName + 'Start') {
- attrStartName = name;
- attrEndName = name.substr(0, name.length - 5) + 'end';
- name = name.substr(0, name.length - 6);
- }
-
- nName = directiveNormalize(name.toLowerCase());
- attrsMap[nName] = name;
- attrs[nName] = value = trim(attr.value);
- if (getBooleanAttrName(node, nName)) {
- attrs[nName] = true; // presence means true
- }
- addAttrInterpolateDirective(node, directives, value, nName);
- addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
- attrEndName);
- }
- }
-
- // use class as directive
- className = node.className;
- if (isString(className) && className !== '') {
- while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
- nName = directiveNormalize(match[2]);
- if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
- attrs[nName] = trim(match[3]);
- }
- className = className.substr(match.index + match[0].length);
- }
- }
- break;
- case 3: /* Text Node */
- addTextInterpolateDirective(directives, node.nodeValue);
- break;
- case 8: /* Comment */
- try {
- match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
- if (match) {
- nName = directiveNormalize(match[1]);
- if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
- attrs[nName] = trim(match[2]);
- }
- }
- } catch (e) {
- // turns out that under some circumstances IE9 throws errors when one attempts to read
- // comment's node value.
- // Just ignore it and continue. (Can't seem to reproduce in test case.)
- }
- break;
- }
-
- directives.sort(byPriority);
- return directives;
- }
-
- /**
- * Given a node with an directive-start it collects all of the siblings until it finds
- * directive-end.
- * @param node
- * @param attrStart
- * @param attrEnd
- * @returns {*}
- */
- function groupScan(node, attrStart, attrEnd) {
- var nodes = [];
- var depth = 0;
- if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
- var startNode = node;
- do {
- if (!node) {
- throw $compileMinErr('uterdir',
- "Unterminated attribute, found '{0}' but no matching '{1}' found.",
- attrStart, attrEnd);
- }
- if (node.nodeType == 1 /** Element **/) {
- if (node.hasAttribute(attrStart)) depth++;
- if (node.hasAttribute(attrEnd)) depth--;
- }
- nodes.push(node);
- node = node.nextSibling;
- } while (depth > 0);
- } else {
- nodes.push(node);
- }
-
- return jqLite(nodes);
- }
-
- /**
- * Wrapper for linking function which converts normal linking function into a grouped
- * linking function.
- * @param linkFn
- * @param attrStart
- * @param attrEnd
- * @returns {Function}
- */
- function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
- return function(scope, element, attrs, controllers, transcludeFn) {
- element = groupScan(element[0], attrStart, attrEnd);
- return linkFn(scope, element, attrs, controllers, transcludeFn);
- };
- }
-
- /**
- * Once the directives have been collected, their compile functions are executed. This method
- * is responsible for inlining directive templates as well as terminating the application
- * of the directives if the terminal directive has been reached.
- *
- * @param {Array} directives Array of collected directives to execute their compile function.
- * this needs to be pre-sorted by priority order.
- * @param {Node} compileNode The raw DOM node to apply the compile functions to
- * @param {Object} templateAttrs The shared attribute function
- * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
- * scope argument is auto-generated to the new
- * child of the transcluded parent scope.
- * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
- * argument has the root jqLite array so that we can replace nodes
- * on it.
- * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
- * compiling the transclusion.
- * @param {Array.} preLinkFns
- * @param {Array.} postLinkFns
- * @param {Object} previousCompileContext Context used for previous compilation of the current
- * node
- * @returns linkFn
- */
- function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
- jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
- previousCompileContext) {
- previousCompileContext = previousCompileContext || {};
-
- var terminalPriority = -Number.MAX_VALUE,
- newScopeDirective,
- controllerDirectives = previousCompileContext.controllerDirectives,
- newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
- templateDirective = previousCompileContext.templateDirective,
- nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
- hasTranscludeDirective = false,
- hasElementTranscludeDirective = false,
- $compileNode = templateAttrs.$$element = jqLite(compileNode),
- directive,
- directiveName,
- $template,
- replaceDirective = originalReplaceDirective,
- childTranscludeFn = transcludeFn,
- linkFn,
- directiveValue;
-
- // executes all directives on the current element
- for(var i = 0, ii = directives.length; i < ii; i++) {
- directive = directives[i];
- var attrStart = directive.$$start;
- var attrEnd = directive.$$end;
-
- // collect multiblock sections
- if (attrStart) {
- $compileNode = groupScan(compileNode, attrStart, attrEnd);
- }
- $template = undefined;
-
- if (terminalPriority > directive.priority) {
- break; // prevent further processing of directives
- }
-
- if (directiveValue = directive.scope) {
- newScopeDirective = newScopeDirective || directive;
-
- // skip the check for directives with async templates, we'll check the derived sync
- // directive when the template arrives
- if (!directive.templateUrl) {
- assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
- $compileNode);
- if (isObject(directiveValue)) {
- newIsolateScopeDirective = directive;
- }
- }
- }
-
- directiveName = directive.name;
-
- if (!directive.templateUrl && directive.controller) {
- directiveValue = directive.controller;
- controllerDirectives = controllerDirectives || {};
- assertNoDuplicate("'" + directiveName + "' controller",
- controllerDirectives[directiveName], directive, $compileNode);
- controllerDirectives[directiveName] = directive;
- }
-
- if (directiveValue = directive.transclude) {
- hasTranscludeDirective = true;
-
- // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
- // This option should only be used by directives that know how to how to safely handle element transclusion,
- // where the transcluded nodes are added or replaced after linking.
- if (!directive.$$tlb) {
- assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
- nonTlbTranscludeDirective = directive;
- }
-
- if (directiveValue == 'element') {
- hasElementTranscludeDirective = true;
- terminalPriority = directive.priority;
- $template = groupScan(compileNode, attrStart, attrEnd);
- $compileNode = templateAttrs.$$element =
- jqLite(document.createComment(' ' + directiveName + ': ' +
- templateAttrs[directiveName] + ' '));
- compileNode = $compileNode[0];
- replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
-
- childTranscludeFn = compile($template, transcludeFn, terminalPriority,
- replaceDirective && replaceDirective.name, {
- // Don't pass in:
- // - controllerDirectives - otherwise we'll create duplicates controllers
- // - newIsolateScopeDirective or templateDirective - combining templates with
- // element transclusion doesn't make sense.
- //
- // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
- // on the same element more than once.
- nonTlbTranscludeDirective: nonTlbTranscludeDirective
- });
- } else {
- $template = jqLite(jqLiteClone(compileNode)).contents();
- $compileNode.empty(); // clear contents
- childTranscludeFn = compile($template, transcludeFn);
- }
- }
-
- if (directive.template) {
- assertNoDuplicate('template', templateDirective, directive, $compileNode);
- templateDirective = directive;
-
- directiveValue = (isFunction(directive.template))
- ? directive.template($compileNode, templateAttrs)
- : directive.template;
-
- directiveValue = denormalizeTemplate(directiveValue);
-
- if (directive.replace) {
- replaceDirective = directive;
- $template = jqLite('
' +
- trim(directiveValue) +
- '
').contents();
- compileNode = $template[0];
-
- if ($template.length != 1 || compileNode.nodeType !== 1) {
- throw $compileMinErr('tplrt',
- "Template for directive '{0}' must have exactly one root element. {1}",
- directiveName, '');
- }
-
- replaceWith(jqCollection, $compileNode, compileNode);
-
- var newTemplateAttrs = {$attr: {}};
-
- // combine directives from the original node and from the template:
- // - take the array of directives for this element
- // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
- // - collect directives from the template and sort them by priority
- // - combine directives as: processed + template + unprocessed
- var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
- var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
-
- if (newIsolateScopeDirective) {
- markDirectivesAsIsolate(templateDirectives);
- }
- directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
- mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
-
- ii = directives.length;
- } else {
- $compileNode.html(directiveValue);
- }
- }
-
- if (directive.templateUrl) {
- assertNoDuplicate('template', templateDirective, directive, $compileNode);
- templateDirective = directive;
-
- if (directive.replace) {
- replaceDirective = directive;
- }
-
- nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
- templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, {
- controllerDirectives: controllerDirectives,
- newIsolateScopeDirective: newIsolateScopeDirective,
- templateDirective: templateDirective,
- nonTlbTranscludeDirective: nonTlbTranscludeDirective
- });
- ii = directives.length;
- } else if (directive.compile) {
- try {
- linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
- if (isFunction(linkFn)) {
- addLinkFns(null, linkFn, attrStart, attrEnd);
- } else if (linkFn) {
- addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
- }
- } catch (e) {
- $exceptionHandler(e, startingTag($compileNode));
- }
- }
-
- if (directive.terminal) {
- nodeLinkFn.terminal = true;
- terminalPriority = Math.max(terminalPriority, directive.priority);
- }
-
- }
-
- nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
- nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn;
-
- // might be normal or delayed nodeLinkFn depending on if templateUrl is present
- return nodeLinkFn;
-
- ////////////////////
-
- function addLinkFns(pre, post, attrStart, attrEnd) {
- if (pre) {
- if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
- pre.require = directive.require;
- if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
- pre = cloneAndAnnotateFn(pre, {isolateScope: true});
- }
- preLinkFns.push(pre);
- }
- if (post) {
- if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
- post.require = directive.require;
- if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
- post = cloneAndAnnotateFn(post, {isolateScope: true});
- }
- postLinkFns.push(post);
- }
- }
-
-
- function getControllers(require, $element, elementControllers) {
- var value, retrievalMethod = 'data', optional = false;
- if (isString(require)) {
- while((value = require.charAt(0)) == '^' || value == '?') {
- require = require.substr(1);
- if (value == '^') {
- retrievalMethod = 'inheritedData';
- }
- optional = optional || value == '?';
- }
- value = null;
-
- if (elementControllers && retrievalMethod === 'data') {
- value = elementControllers[require];
- }
- value = value || $element[retrievalMethod]('$' + require + 'Controller');
-
- if (!value && !optional) {
- throw $compileMinErr('ctreq',
- "Controller '{0}', required by directive '{1}', can't be found!",
- require, directiveName);
- }
- return value;
- } else if (isArray(require)) {
- value = [];
- forEach(require, function(require) {
- value.push(getControllers(require, $element, elementControllers));
- });
- }
- return value;
- }
-
-
- function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
- var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
-
- if (compileNode === linkNode) {
- attrs = templateAttrs;
- } else {
- attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
- }
- $element = attrs.$$element;
-
- if (newIsolateScopeDirective) {
- var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
- var $linkNode = jqLite(linkNode);
-
- isolateScope = scope.$new(true);
-
- if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) {
- $linkNode.data('$isolateScope', isolateScope) ;
- } else {
- $linkNode.data('$isolateScopeNoTemplate', isolateScope);
- }
-
-
-
- safeAddClass($linkNode, 'ng-isolate-scope');
-
- forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
- var match = definition.match(LOCAL_REGEXP) || [],
- attrName = match[3] || scopeName,
- optional = (match[2] == '?'),
- mode = match[1], // @, =, or &
- lastValue,
- parentGet, parentSet, compare;
-
- isolateScope.$$isolateBindings[scopeName] = mode + attrName;
-
- switch (mode) {
-
- case '@':
- attrs.$observe(attrName, function(value) {
- isolateScope[scopeName] = value;
- });
- attrs.$$observers[attrName].$$scope = scope;
- if( attrs[attrName] ) {
- // If the attribute has been provided then we trigger an interpolation to ensure
- // the value is there for use in the link fn
- isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
- }
- break;
-
- case '=':
- if (optional && !attrs[attrName]) {
- return;
- }
- parentGet = $parse(attrs[attrName]);
- if (parentGet.literal) {
- compare = equals;
- } else {
- compare = function(a,b) { return a === b; };
- }
- parentSet = parentGet.assign || function() {
- // reset the change, or we will throw this exception on every $digest
- lastValue = isolateScope[scopeName] = parentGet(scope);
- throw $compileMinErr('nonassign',
- "Expression '{0}' used with directive '{1}' is non-assignable!",
- attrs[attrName], newIsolateScopeDirective.name);
- };
- lastValue = isolateScope[scopeName] = parentGet(scope);
- isolateScope.$watch(function parentValueWatch() {
- var parentValue = parentGet(scope);
- if (!compare(parentValue, isolateScope[scopeName])) {
- // we are out of sync and need to copy
- if (!compare(parentValue, lastValue)) {
- // parent changed and it has precedence
- isolateScope[scopeName] = parentValue;
- } else {
- // if the parent can be assigned then do so
- parentSet(scope, parentValue = isolateScope[scopeName]);
- }
- }
- return lastValue = parentValue;
- }, null, parentGet.literal);
- break;
-
- case '&':
- parentGet = $parse(attrs[attrName]);
- isolateScope[scopeName] = function(locals) {
- return parentGet(scope, locals);
- };
- break;
-
- default:
- throw $compileMinErr('iscp',
- "Invalid isolate scope definition for directive '{0}'." +
- " Definition: {... {1}: '{2}' ...}",
- newIsolateScopeDirective.name, scopeName, definition);
- }
- });
- }
- transcludeFn = boundTranscludeFn && controllersBoundTransclude;
- if (controllerDirectives) {
- forEach(controllerDirectives, function(directive) {
- var locals = {
- $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
- $element: $element,
- $attrs: attrs,
- $transclude: transcludeFn
- }, controllerInstance;
-
- controller = directive.controller;
- if (controller == '@') {
- controller = attrs[directive.name];
- }
-
- controllerInstance = $controller(controller, locals);
- // For directives with element transclusion the element is a comment,
- // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
- // clean up (http://bugs.jquery.com/ticket/8335).
- // Instead, we save the controllers for the element in a local hash and attach to .data
- // later, once we have the actual element.
- elementControllers[directive.name] = controllerInstance;
- if (!hasElementTranscludeDirective) {
- $element.data('$' + directive.name + 'Controller', controllerInstance);
- }
-
- if (directive.controllerAs) {
- locals.$scope[directive.controllerAs] = controllerInstance;
- }
- });
- }
-
- // PRELINKING
- for(i = 0, ii = preLinkFns.length; i < ii; i++) {
- try {
- linkFn = preLinkFns[i];
- linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
- linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
- } catch (e) {
- $exceptionHandler(e, startingTag($element));
- }
- }
-
- // RECURSION
- // We only pass the isolate scope, if the isolate directive has a template,
- // otherwise the child elements do not belong to the isolate directive.
- var scopeToChild = scope;
- if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
- scopeToChild = isolateScope;
- }
- childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
-
- // POSTLINKING
- for(i = postLinkFns.length - 1; i >= 0; i--) {
- try {
- linkFn = postLinkFns[i];
- linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
- linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
- } catch (e) {
- $exceptionHandler(e, startingTag($element));
- }
- }
-
- // This is the function that is injected as `$transclude`.
- function controllersBoundTransclude(scope, cloneAttachFn) {
- var transcludeControllers;
-
- // no scope passed
- if (arguments.length < 2) {
- cloneAttachFn = scope;
- scope = undefined;
- }
-
- if (hasElementTranscludeDirective) {
- transcludeControllers = elementControllers;
- }
-
- return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
- }
- }
- }
-
- function markDirectivesAsIsolate(directives) {
- // mark all directives as needing isolate scope.
- for (var j = 0, jj = directives.length; j < jj; j++) {
- directives[j] = inherit(directives[j], {$$isolateScope: true});
- }
- }
-
- /**
- * looks up the directive and decorates it with exception handling and proper parameters. We
- * call this the boundDirective.
- *
- * @param {string} name name of the directive to look up.
- * @param {string} location The directive must be found in specific format.
- * String containing any of theses characters:
- *
- * * `E`: element name
- * * `A': attribute
- * * `C`: class
- * * `M`: comment
- * @returns true if directive was added.
- */
- function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
- endAttrName) {
- if (name === ignoreDirective) return null;
- var match = null;
- if (hasDirectives.hasOwnProperty(name)) {
- for(var directive, directives = $injector.get(name + Suffix),
- i = 0, ii = directives.length; i directive.priority) &&
- directive.restrict.indexOf(location) != -1) {
- if (startAttrName) {
- directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
- }
- tDirectives.push(directive);
- match = directive;
- }
- } catch(e) { $exceptionHandler(e); }
- }
- }
- return match;
- }
-
-
- /**
- * When the element is replaced with HTML template then the new attributes
- * on the template need to be merged with the existing attributes in the DOM.
- * The desired effect is to have both of the attributes present.
- *
- * @param {object} dst destination attributes (original DOM)
- * @param {object} src source attributes (from the directive template)
- */
- function mergeTemplateAttributes(dst, src) {
- var srcAttr = src.$attr,
- dstAttr = dst.$attr,
- $element = dst.$$element;
-
- // reapply the old attributes to the new element
- forEach(dst, function(value, key) {
- if (key.charAt(0) != '$') {
- if (src[key]) {
- value += (key === 'style' ? ';' : ' ') + src[key];
- }
- dst.$set(key, value, true, srcAttr[key]);
- }
- });
-
- // copy the new attributes on the old attrs object
- forEach(src, function(value, key) {
- if (key == 'class') {
- safeAddClass($element, value);
- dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
- } else if (key == 'style') {
- $element.attr('style', $element.attr('style') + ';' + value);
- dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
- // `dst` will never contain hasOwnProperty as DOM parser won't let it.
- // You will get an "InvalidCharacterError: DOM Exception 5" error if you
- // have an attribute like "has-own-property" or "data-has-own-property", etc.
- } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
- dst[key] = value;
- dstAttr[key] = srcAttr[key];
- }
- });
- }
-
-
- function compileTemplateUrl(directives, $compileNode, tAttrs,
- $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
- var linkQueue = [],
- afterTemplateNodeLinkFn,
- afterTemplateChildLinkFn,
- beforeTemplateCompileNode = $compileNode[0],
- origAsyncDirective = directives.shift(),
- // The fact that we have to copy and patch the directive seems wrong!
- derivedSyncDirective = extend({}, origAsyncDirective, {
- templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
- }),
- templateUrl = (isFunction(origAsyncDirective.templateUrl))
- ? origAsyncDirective.templateUrl($compileNode, tAttrs)
- : origAsyncDirective.templateUrl;
-
- $compileNode.empty();
-
- $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
- success(function(content) {
- var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
-
- content = denormalizeTemplate(content);
-
- if (origAsyncDirective.replace) {
- $template = jqLite('
' + trim(content) + '
').contents();
- compileNode = $template[0];
-
- if ($template.length != 1 || compileNode.nodeType !== 1) {
- throw $compileMinErr('tplrt',
- "Template for directive '{0}' must have exactly one root element. {1}",
- origAsyncDirective.name, templateUrl);
- }
-
- tempTemplateAttrs = {$attr: {}};
- replaceWith($rootElement, $compileNode, compileNode);
- var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
-
- if (isObject(origAsyncDirective.scope)) {
- markDirectivesAsIsolate(templateDirectives);
- }
- directives = templateDirectives.concat(directives);
- mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
- } else {
- compileNode = beforeTemplateCompileNode;
- $compileNode.html(content);
- }
-
- directives.unshift(derivedSyncDirective);
-
- afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
- childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
- previousCompileContext);
- forEach($rootElement, function(node, i) {
- if (node == compileNode) {
- $rootElement[i] = $compileNode[0];
- }
- });
- afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
-
-
- while(linkQueue.length) {
- var scope = linkQueue.shift(),
- beforeTemplateLinkNode = linkQueue.shift(),
- linkRootElement = linkQueue.shift(),
- boundTranscludeFn = linkQueue.shift(),
- linkNode = $compileNode[0];
-
- if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
- // it was cloned therefore we have to clone as well.
- linkNode = jqLiteClone(compileNode);
- replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
- }
- if (afterTemplateNodeLinkFn.transclude) {
- childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude);
- } else {
- childBoundTranscludeFn = boundTranscludeFn;
- }
- afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
- childBoundTranscludeFn);
- }
- linkQueue = null;
- }).
- error(function(response, code, headers, config) {
- throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
- });
-
- return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
- if (linkQueue) {
- linkQueue.push(scope);
- linkQueue.push(node);
- linkQueue.push(rootElement);
- linkQueue.push(boundTranscludeFn);
- } else {
- afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn);
- }
- };
- }
-
-
- /**
- * Sorting function for bound directives.
- */
- function byPriority(a, b) {
- var diff = b.priority - a.priority;
- if (diff !== 0) return diff;
- if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
- return a.index - b.index;
- }
-
-
- function assertNoDuplicate(what, previousDirective, directive, element) {
- if (previousDirective) {
- throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
- previousDirective.name, directive.name, what, startingTag(element));
- }
- }
-
-
- function addTextInterpolateDirective(directives, text) {
- var interpolateFn = $interpolate(text, true);
- if (interpolateFn) {
- directives.push({
- priority: 0,
- compile: valueFn(function textInterpolateLinkFn(scope, node) {
- var parent = node.parent(),
- bindings = parent.data('$binding') || [];
- bindings.push(interpolateFn);
- safeAddClass(parent.data('$binding', bindings), 'ng-binding');
- scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
- node[0].nodeValue = value;
- });
- })
- });
- }
- }
-
-
- function getTrustedContext(node, attrNormalizedName) {
- if (attrNormalizedName == "srcdoc") {
- return $sce.HTML;
- }
- var tag = nodeName_(node);
- // maction[xlink:href] can source SVG. It's not limited to .
- if (attrNormalizedName == "xlinkHref" ||
- (tag == "FORM" && attrNormalizedName == "action") ||
- (tag != "IMG" && (attrNormalizedName == "src" ||
- attrNormalizedName == "ngSrc"))) {
- return $sce.RESOURCE_URL;
- }
- }
-
-
- function addAttrInterpolateDirective(node, directives, value, name) {
- var interpolateFn = $interpolate(value, true);
-
- // no interpolation found -> ignore
- if (!interpolateFn) return;
-
-
- if (name === "multiple" && nodeName_(node) === "SELECT") {
- throw $compileMinErr("selmulti",
- "Binding to the 'multiple' attribute is not supported. Element: {0}",
- startingTag(node));
- }
-
- directives.push({
- priority: 100,
- compile: function() {
- return {
- pre: function attrInterpolatePreLinkFn(scope, element, attr) {
- var $$observers = (attr.$$observers || (attr.$$observers = {}));
-
- if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
- throw $compileMinErr('nodomevents',
- "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
- "ng- versions (such as ng-click instead of onclick) instead.");
- }
-
- // we need to interpolate again, in case the attribute value has been updated
- // (e.g. by another directive's compile function)
- interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
-
- // if attribute was updated so that there is no interpolation going on we don't want to
- // register any observers
- if (!interpolateFn) return;
-
- // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
- // actual attr value
- attr[name] = interpolateFn(scope);
- ($$observers[name] || ($$observers[name] = [])).$$inter = true;
- (attr.$$observers && attr.$$observers[name].$$scope || scope).
- $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
- //special case for class attribute addition + removal
- //so that class changes can tap into the animation
- //hooks provided by the $animate service. Be sure to
- //skip animations when the first digest occurs (when
- //both the new and the old values are the same) since
- //the CSS classes are the non-interpolated values
- if(name === 'class' && newValue != oldValue) {
- attr.$updateClass(newValue, oldValue);
- } else {
- attr.$set(name, newValue);
- }
- });
- }
- };
- }
- });
- }
-
-
- /**
- * This is a special jqLite.replaceWith, which can replace items which
- * have no parents, provided that the containing jqLite collection is provided.
- *
- * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
- * in the root of the tree.
- * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
- * the shell, but replace its DOM node reference.
- * @param {Node} newNode The new DOM node.
- */
- function replaceWith($rootElement, elementsToRemove, newNode) {
- var firstElementToRemove = elementsToRemove[0],
- removeCount = elementsToRemove.length,
- parent = firstElementToRemove.parentNode,
- i, ii;
-
- if ($rootElement) {
- for(i = 0, ii = $rootElement.length; i < ii; i++) {
- if ($rootElement[i] == firstElementToRemove) {
- $rootElement[i++] = newNode;
- for (var j = i, j2 = j + removeCount - 1,
- jj = $rootElement.length;
- j < jj; j++, j2++) {
- if (j2 < jj) {
- $rootElement[j] = $rootElement[j2];
- } else {
- delete $rootElement[j];
- }
- }
- $rootElement.length -= removeCount - 1;
- break;
- }
- }
- }
-
- if (parent) {
- parent.replaceChild(newNode, firstElementToRemove);
- }
- var fragment = document.createDocumentFragment();
- fragment.appendChild(firstElementToRemove);
- newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
- for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
- var element = elementsToRemove[k];
- jqLite(element).remove(); // must do this way to clean up expando
- fragment.appendChild(element);
- delete elementsToRemove[k];
- }
-
- elementsToRemove[0] = newNode;
- elementsToRemove.length = 1;
- }
-
-
- function cloneAndAnnotateFn(fn, annotation) {
- return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
- }
- }];
-}
-
-var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
-/**
- * Converts all accepted directives format into proper directive name.
- * All of these will become 'myDirective':
- * my:Directive
- * my-directive
- * x-my-directive
- * data-my:directive
- *
- * Also there is special case for Moz prefix starting with upper case letter.
- * @param name Name to normalize
- */
-function directiveNormalize(name) {
- return camelCase(name.replace(PREFIX_REGEXP, ''));
-}
-
-/**
- * @ngdoc object
- * @name ng.$compile.directive.Attributes
- *
- * @description
- * A shared object between directive compile / linking functions which contains normalized DOM
- * element attributes. The values reflect current binding state `{{ }}`. The normalization is
- * needed since all of these are treated as equivalent in Angular:
- *
- *
- */
-
-/**
- * @ngdoc property
- * @name ng.$compile.directive.Attributes#$attr
- * @propertyOf ng.$compile.directive.Attributes
- * @returns {object} A map of DOM element attribute names to the normalized name. This is
- * needed to do reverse lookup from normalized name back to actual name.
- */
-
-
-/**
- * @ngdoc function
- * @name ng.$compile.directive.Attributes#$set
- * @methodOf ng.$compile.directive.Attributes
- * @function
- *
- * @description
- * Set DOM element attribute value.
- *
- *
- * @param {string} name Normalized element attribute name of the property to modify. The name is
- * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
- * property to the original name.
- * @param {string} value Value to set the attribute to. The value can be an interpolated string.
- */
-
-
-
-/**
- * Closure compiler type information
- */
-
-function nodesetLinkingFn(
- /* angular.Scope */ scope,
- /* NodeList */ nodeList,
- /* Element */ rootElement,
- /* function(Function) */ boundTranscludeFn
-){}
-
-function directiveLinkingFn(
- /* nodesetLinkingFn */ nodesetLinkingFn,
- /* angular.Scope */ scope,
- /* Node */ node,
- /* Element */ rootElement,
- /* function(Function) */ boundTranscludeFn
-){}
-
-function tokenDifference(str1, str2) {
- var values = '',
- tokens1 = str1.split(/\s+/),
- tokens2 = str2.split(/\s+/);
-
- outer:
- for(var i = 0; i < tokens1.length; i++) {
- var token = tokens1[i];
- for(var j = 0; j < tokens2.length; j++) {
- if(token == tokens2[j]) continue outer;
- }
- values += (values.length > 0 ? ' ' : '') + token;
- }
- return values;
-}
-
-/**
- * @ngdoc object
- * @name ng.$controllerProvider
- * @description
- * The {@link ng.$controller $controller service} is used by Angular to create new
- * controllers.
- *
- * This provider allows controller registration via the
- * {@link ng.$controllerProvider#methods_register register} method.
- */
-function $ControllerProvider() {
- var controllers = {},
- CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
-
-
- /**
- * @ngdoc function
- * @name ng.$controllerProvider#register
- * @methodOf ng.$controllerProvider
- * @param {string|Object} name Controller name, or an object map of controllers where the keys are
- * the names and the values are the constructors.
- * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
- * annotations in the array notation).
- */
- this.register = function(name, constructor) {
- assertNotHasOwnProperty(name, 'controller');
- if (isObject(name)) {
- extend(controllers, name);
- } else {
- controllers[name] = constructor;
- }
- };
-
-
- this.$get = ['$injector', '$window', function($injector, $window) {
-
- /**
- * @ngdoc function
- * @name ng.$controller
- * @requires $injector
- *
- * @param {Function|string} constructor If called with a function then it's considered to be the
- * controller constructor function. Otherwise it's considered to be a string which is used
- * to retrieve the controller constructor using the following steps:
- *
- * * check if a controller with given name is registered via `$controllerProvider`
- * * check if evaluating the string on the current scope returns a constructor
- * * check `window[constructor]` on the global `window` object
- *
- * @param {Object} locals Injection locals for Controller.
- * @return {Object} Instance of given controller.
- *
- * @description
- * `$controller` service is responsible for instantiating controllers.
- *
- * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
- * a service, so that one can override this service with {@link https://gist.github.com/1649788
- * BC version}.
- */
- return function(expression, locals) {
- var instance, match, constructor, identifier;
-
- if(isString(expression)) {
- match = expression.match(CNTRL_REG),
- constructor = match[1],
- identifier = match[3];
- expression = controllers.hasOwnProperty(constructor)
- ? controllers[constructor]
- : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
-
- assertArgFn(expression, constructor, true);
- }
-
- instance = $injector.instantiate(expression, locals);
-
- if (identifier) {
- if (!(locals && typeof locals.$scope == 'object')) {
- throw minErr('$controller')('noscp',
- "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
- constructor || expression.name, identifier);
- }
-
- locals.$scope[identifier] = instance;
- }
-
- return instance;
- };
- }];
-}
-
-/**
- * @ngdoc object
- * @name ng.$document
- * @requires $window
- *
- * @description
- * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
- */
-function $DocumentProvider(){
- this.$get = ['$window', function(window){
- return jqLite(window.document);
- }];
-}
-
-/**
- * @ngdoc function
- * @name ng.$exceptionHandler
- * @requires $log
- *
- * @description
- * Any uncaught exception in angular expressions is delegated to this service.
- * The default implementation simply delegates to `$log.error` which logs it into
- * the browser console.
- *
- * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
- * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
- *
- * ## Example:
- *
- *
- * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
- * return function (exception, cause) {
- * exception.message += ' (caused by "' + cause + '")';
- * throw exception;
- * };
- * });
- *
- *
- * This example will override the normal action of `$exceptionHandler`, to make angular
- * exceptions fail hard when they happen, instead of just logging to the console.
- *
- * @param {Error} exception Exception associated with the error.
- * @param {string=} cause optional information about the context in which
- * the error was thrown.
- *
- */
-function $ExceptionHandlerProvider() {
- this.$get = ['$log', function($log) {
- return function(exception, cause) {
- $log.error.apply($log, arguments);
- };
- }];
-}
-
-/**
- * Parse headers into key value object
- *
- * @param {string} headers Raw headers as a string
- * @returns {Object} Parsed headers as key value object
- */
-function parseHeaders(headers) {
- var parsed = {}, key, val, i;
-
- if (!headers) return parsed;
-
- forEach(headers.split('\n'), function(line) {
- i = line.indexOf(':');
- key = lowercase(trim(line.substr(0, i)));
- val = trim(line.substr(i + 1));
-
- if (key) {
- if (parsed[key]) {
- parsed[key] += ', ' + val;
- } else {
- parsed[key] = val;
- }
- }
- });
-
- return parsed;
-}
-
-
-/**
- * Returns a function that provides access to parsed headers.
- *
- * Headers are lazy parsed when first requested.
- * @see parseHeaders
- *
- * @param {(string|Object)} headers Headers to provide access to.
- * @returns {function(string=)} Returns a getter function which if called with:
- *
- * - if called with single an argument returns a single header value or null
- * - if called with no arguments returns an object containing all headers.
- */
-function headersGetter(headers) {
- var headersObj = isObject(headers) ? headers : undefined;
-
- return function(name) {
- if (!headersObj) headersObj = parseHeaders(headers);
-
- if (name) {
- return headersObj[lowercase(name)] || null;
- }
-
- return headersObj;
- };
-}
-
-
-/**
- * Chain all given functions
- *
- * This function is used for both request and response transforming
- *
- * @param {*} data Data to transform.
- * @param {function(string=)} headers Http headers getter fn.
- * @param {(function|Array.)} fns Function or an array of functions.
- * @returns {*} Transformed data.
- */
-function transformData(data, headers, fns) {
- if (isFunction(fns))
- return fns(data, headers);
-
- forEach(fns, function(fn) {
- data = fn(data, headers);
- });
-
- return data;
-}
-
-
-function isSuccess(status) {
- return 200 <= status && status < 300;
-}
-
-
-function $HttpProvider() {
- var JSON_START = /^\s*(\[|\{[^\{])/,
- JSON_END = /[\}\]]\s*$/,
- PROTECTION_PREFIX = /^\)\]\}',?\n/,
- CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
-
- var defaults = this.defaults = {
- // transform incoming response data
- transformResponse: [function(data) {
- if (isString(data)) {
- // strip json vulnerability protection prefix
- data = data.replace(PROTECTION_PREFIX, '');
- if (JSON_START.test(data) && JSON_END.test(data))
- data = fromJson(data);
- }
- return data;
- }],
-
- // transform outgoing request data
- transformRequest: [function(d) {
- return isObject(d) && !isFile(d) ? toJson(d) : d;
- }],
-
- // default headers
- headers: {
- common: {
- 'Accept': 'application/json, text/plain, */*'
- },
- post: copy(CONTENT_TYPE_APPLICATION_JSON),
- put: copy(CONTENT_TYPE_APPLICATION_JSON),
- patch: copy(CONTENT_TYPE_APPLICATION_JSON)
- },
-
- xsrfCookieName: 'XSRF-TOKEN',
- xsrfHeaderName: 'X-XSRF-TOKEN'
- };
-
- /**
- * Are ordered by request, i.e. they are applied in the same order as the
- * array, on request, but reverse order, on response.
- */
- var interceptorFactories = this.interceptors = [];
-
- /**
- * For historical reasons, response interceptors are ordered by the order in which
- * they are applied to the response. (This is the opposite of interceptorFactories)
- */
- var responseInterceptorFactories = this.responseInterceptors = [];
-
- this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
- function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
-
- var defaultCache = $cacheFactory('$http');
-
- /**
- * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
- * The reversal is needed so that we can build up the interception chain around the
- * server request.
- */
- var reversedInterceptors = [];
-
- forEach(interceptorFactories, function(interceptorFactory) {
- reversedInterceptors.unshift(isString(interceptorFactory)
- ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
- });
-
- forEach(responseInterceptorFactories, function(interceptorFactory, index) {
- var responseFn = isString(interceptorFactory)
- ? $injector.get(interceptorFactory)
- : $injector.invoke(interceptorFactory);
-
- /**
- * Response interceptors go before "around" interceptors (no real reason, just
- * had to pick one.) But they are already reversed, so we can't use unshift, hence
- * the splice.
- */
- reversedInterceptors.splice(index, 0, {
- response: function(response) {
- return responseFn($q.when(response));
- },
- responseError: function(response) {
- return responseFn($q.reject(response));
- }
- });
- });
-
-
- /**
- * @ngdoc function
- * @name ng.$http
- * @requires $httpBackend
- * @requires $browser
- * @requires $cacheFactory
- * @requires $rootScope
- * @requires $q
- * @requires $injector
- *
- * @description
- * The `$http` service is a core Angular service that facilitates communication with the remote
- * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest
- * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
- *
- * For unit testing applications that use `$http` service, see
- * {@link ngMock.$httpBackend $httpBackend mock}.
- *
- * For a higher level of abstraction, please check out the {@link ngResource.$resource
- * $resource} service.
- *
- * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
- * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
- * it is important to familiarize yourself with these APIs and the guarantees they provide.
- *
- *
- * # General usage
- * The `$http` service is a function which takes a single argument — a configuration object —
- * that is used to generate an HTTP request and returns a {@link ng.$q promise}
- * with two $http specific methods: `success` and `error`.
- *
- *
- * $http({method: 'GET', url: '/someUrl'}).
- * success(function(data, status, headers, config) {
- * // this callback will be called asynchronously
- * // when the response is available
- * }).
- * error(function(data, status, headers, config) {
- * // called asynchronously if an error occurs
- * // or server returns response with an error status.
- * });
- *
- *
- * Since the returned value of calling the $http function is a `promise`, you can also use
- * the `then` method to register callbacks, and these callbacks will receive a single argument –
- * an object representing the response. See the API signature and type info below for more
- * details.
- *
- * A response status code between 200 and 299 is considered a success status and
- * will result in the success callback being called. Note that if the response is a redirect,
- * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
- * called for such responses.
- *
- * # Calling $http from outside AngularJS
- * The `$http` service will not actually send the request until the next `$digest()` is
- * executed. Normally this is not an issue, since almost all the time your call to `$http` will
- * be from within a `$apply()` block.
- * If you are calling `$http` from outside Angular, then you should wrap it in a call to
- * `$apply` to cause a $digest to occur and also to handle errors in the block correctly.
- *
- * ```
- * $scope.$apply(function() {
- * $http(...);
- * });
- * ```
- *
- * # Writing Unit Tests that use $http
- * When unit testing you are mostly responsible for scheduling the `$digest` cycle. If you do
- * not trigger a `$digest` before calling `$httpBackend.flush()` then the request will not have
- * been made and `$httpBackend.expect(...)` expectations will fail. The solution is to run the
- * code that calls the `$http()` method inside a $apply block as explained in the previous
- * section.
- *
- * ```
- * $httpBackend.expectGET(...);
- * $scope.$apply(function() {
- * $http.get(...);
- * });
- * $httpBackend.flush();
- * ```
- *
- * # Shortcut methods
- *
- * Since all invocations of the $http service require passing in an HTTP method and URL, and
- * POST/PUT requests require request data to be provided as well, shortcut methods
- * were created:
- *
- *
- *
- * Complete list of shortcut methods:
- *
- * - {@link ng.$http#methods_get $http.get}
- * - {@link ng.$http#methods_head $http.head}
- * - {@link ng.$http#methods_post $http.post}
- * - {@link ng.$http#methods_put $http.put}
- * - {@link ng.$http#methods_delete $http.delete}
- * - {@link ng.$http#methods_jsonp $http.jsonp}
- *
- *
- * # Setting HTTP Headers
- *
- * The $http service will automatically add certain HTTP headers to all requests. These defaults
- * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
- * object, which currently contains this default configuration:
- *
- * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
- * - `Accept: application/json, text/plain, * / *`
- * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
- * - `Content-Type: application/json`
- * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
- * - `Content-Type: application/json`
- *
- * To add or overwrite these defaults, simply add or remove a property from these configuration
- * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
- * with the lowercased HTTP method name as the key, e.g.
- * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
- *
- * The defaults can also be set at runtime via the `$http.defaults` object in the same
- * fashion. For example:
- *
- * ```
- * module.run(function($http) {
- * $http.defaults.headers.common.Authentication = 'Basic YmVlcDpib29w'
- * });
- * ```
- *
- * In addition, you can supply a `headers` property in the config object passed when
- * calling `$http(config)`, which overrides the defaults without changing them globally.
- *
- *
- * # Transforming Requests and Responses
- *
- * Both requests and responses can be transformed using transform functions. By default, Angular
- * applies these transformations:
- *
- * Request transformations:
- *
- * - If the `data` property of the request configuration object contains an object, serialize it
- * into JSON format.
- *
- * Response transformations:
- *
- * - If XSRF prefix is detected, strip it (see Security Considerations section below).
- * - If JSON response is detected, deserialize it using a JSON parser.
- *
- * To globally augment or override the default transforms, modify the
- * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
- * properties. These properties are by default an array of transform functions, which allows you
- * to `push` or `unshift` a new transformation function into the transformation chain. You can
- * also decide to completely override any default transformations by assigning your
- * transformation functions to these properties directly without the array wrapper. These defaults
- * are again available on the $http factory at run-time, which may be useful if you have run-time
- * services you wish to be involved in your transformations.
- *
- * Similarly, to locally override the request/response transforms, augment the
- * `transformRequest` and/or `transformResponse` properties of the configuration object passed
- * into `$http`.
- *
- *
- * # Caching
- *
- * To enable caching, set the request configuration `cache` property to `true` (to use default
- * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
- * When the cache is enabled, `$http` stores the response from the server in the specified
- * cache. The next time the same request is made, the response is served from the cache without
- * sending a request to the server.
- *
- * Note that even if the response is served from cache, delivery of the data is asynchronous in
- * the same way that real requests are.
- *
- * If there are multiple GET requests for the same URL that should be cached using the same
- * cache, but the cache is not populated yet, only one request to the server will be made and
- * the remaining requests will be fulfilled using the response from the first request.
- *
- * You can change the default cache to a new object (built with
- * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
- * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
- * their `cache` property to `true` will now use this cache object.
- *
- * If you set the default cache to `false` then only requests that specify their own custom
- * cache object will be cached.
- *
- * # Interceptors
- *
- * Before you start creating interceptors, be sure to understand the
- * {@link ng.$q $q and deferred/promise APIs}.
- *
- * For purposes of global error handling, authentication, or any kind of synchronous or
- * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
- * able to intercept requests before they are handed to the server and
- * responses before they are handed over to the application code that
- * initiated these requests. The interceptors leverage the {@link ng.$q
- * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
- *
- * The interceptors are service factories that are registered with the `$httpProvider` by
- * adding them to the `$httpProvider.interceptors` array. The factory is called and
- * injected with dependencies (if specified) and returns the interceptor.
- *
- * There are two kinds of interceptors (and two kinds of rejection interceptors):
- *
- * * `request`: interceptors get called with http `config` object. The function is free to
- * modify the `config` or create a new one. The function needs to return the `config`
- * directly or as a promise.
- * * `requestError`: interceptor gets called when a previous interceptor threw an error or
- * resolved with a rejection.
- * * `response`: interceptors get called with http `response` object. The function is free to
- * modify the `response` or create a new one. The function needs to return the `response`
- * directly or as a promise.
- * * `responseError`: interceptor gets called when a previous interceptor threw an error or
- * resolved with a rejection.
- *
- *
- *
- *
- * # Response interceptors (DEPRECATED)
- *
- * Before you start creating interceptors, be sure to understand the
- * {@link ng.$q $q and deferred/promise APIs}.
- *
- * For purposes of global error handling, authentication or any kind of synchronous or
- * asynchronous preprocessing of received responses, it is desirable to be able to intercept
- * responses for http requests before they are handed over to the application code that
- * initiated these requests. The response interceptors leverage the {@link ng.$q
- * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
- *
- * The interceptors are service factories that are registered with the $httpProvider by
- * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
- * injected with dependencies (if specified) and returns the interceptor — a function that
- * takes a {@link ng.$q promise} and returns the original or a new promise.
- *
- *
- * // register the interceptor as a service
- * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
- * return function(promise) {
- * return promise.then(function(response) {
- * // do something on success
- * return response;
- * }, function(response) {
- * // do something on error
- * if (canRecover(response)) {
- * return responseOrNewPromise
- * }
- * return $q.reject(response);
- * });
- * }
- * });
- *
- * $httpProvider.responseInterceptors.push('myHttpInterceptor');
- *
- *
- * // register the interceptor via an anonymous factory
- * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
- * return function(promise) {
- * // same as above
- * }
- * });
- *
- *
- *
- * # Security Considerations
- *
- * When designing web applications, consider security threats from:
- *
- * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
- * JSON vulnerability}
- * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
- *
- * Both server and the client must cooperate in order to eliminate these threats. Angular comes
- * pre-configured with strategies that address these issues, but for this to work backend server
- * cooperation is required.
- *
- * ## JSON Vulnerability Protection
- *
- * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
- * JSON vulnerability} allows third party website to turn your JSON resource URL into
- * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To
- * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
- * Angular will automatically strip the prefix before processing it as JSON.
- *
- * For example if your server needs to return:
- *
- * ['one','two']
- *
- *
- * which is vulnerable to attack, your server can return:
- *
- * )]}',
- * ['one','two']
- *
- *
- * Angular will strip the prefix, before processing the JSON.
- *
- *
- * ## Cross Site Request Forgery (XSRF) Protection
- *
- * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
- * an unauthorized site can gain your user's private data. Angular provides a mechanism
- * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
- * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
- * JavaScript that runs on your domain could read the cookie, your server can be assured that
- * the XHR came from JavaScript running on your domain. The header will not be set for
- * cross-domain requests.
- *
- * To take advantage of this, your server needs to set a token in a JavaScript readable session
- * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
- * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
- * that only JavaScript running on your domain could have sent the request. The token must be
- * unique for each user and must be verifiable by the server (to prevent the JavaScript from
- * making up its own tokens). We recommend that the token is a digest of your site's
- * authentication cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt}
- * for added security.
- *
- * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
- * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
- * or the per-request config object.
- *
- *
- * @param {object} config Object describing the request to be made and how it should be
- * processed. The object has following properties:
- *
- * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
- * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
- * - **params** – `{Object.}` – Map of strings or objects which will be turned
- * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
- * JSONified.
- * - **data** – `{string|Object}` – Data to be sent as the request message data.
- * - **headers** – `{Object}` – Map of strings or functions which return strings representing
- * HTTP headers to send to the server. If the return value of a function is null, the
- * header will not be sent.
- * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
- * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
- * - **transformRequest** –
- * `{function(data, headersGetter)|Array.}` –
- * transform function or an array of such functions. The transform function takes the http
- * request body and headers and returns its transformed (typically serialized) version.
- * - **transformResponse** –
- * `{function(data, headersGetter)|Array.}` –
- * transform function or an array of such functions. The transform function takes the http
- * response body and headers and returns its transformed (typically deserialized) version.
- * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
- * GET request, otherwise if a cache instance built with
- * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
- * caching.
- * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
- * that should abort the request when resolved.
- * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
- * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
- * requests with credentials} for more information.
- * - **responseType** - `{string}` - see {@link
- * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
- *
- * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
- * standard `then` method and two http specific methods: `success` and `error`. The `then`
- * method takes two arguments a success and an error callback which will be called with a
- * response object. The `success` and `error` methods take a single argument - a function that
- * will be called when the request succeeds or fails respectively. The arguments passed into
- * these functions are destructured representation of the response object passed into the
- * `then` method. The response object has these properties:
- *
- * - **data** – `{string|Object}` – The response body transformed with the transform
- * functions.
- * - **status** – `{number}` – HTTP status code of the response.
- * - **headers** – `{function([headerName])}` – Header getter function.
- * - **config** – `{Object}` – The configuration object that was used to generate the request.
- *
- * @property {Array.
- *
- * @param {function()} fn A function that should be called repeatedly.
- * @param {number} delay Number of milliseconds between each function call.
- * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
- * indefinitely.
- * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
- * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
- * @returns {promise} A promise which will be notified on each iteration.
- *
- * @example
-
-
-
-
-
-
- Date format:
- Current time is:
-
- Blood 1 : {{blood_1}}
- Blood 2 : {{blood_2}}
-
-
-
-
-
-
-
-
- */
- function interval(fn, delay, count, invokeApply) {
- var setInterval = $window.setInterval,
- clearInterval = $window.clearInterval,
- deferred = $q.defer(),
- promise = deferred.promise,
- iteration = 0,
- skipApply = (isDefined(invokeApply) && !invokeApply);
-
- count = isDefined(count) ? count : 0,
-
- promise.then(null, null, fn);
-
- promise.$$intervalId = setInterval(function tick() {
- deferred.notify(iteration++);
-
- if (count > 0 && iteration >= count) {
- deferred.resolve(iteration);
- clearInterval(promise.$$intervalId);
- delete intervals[promise.$$intervalId];
- }
-
- if (!skipApply) $rootScope.$apply();
-
- }, delay);
-
- intervals[promise.$$intervalId] = deferred;
-
- return promise;
- }
-
-
- /**
- * @ngdoc function
- * @name ng.$interval#cancel
- * @methodOf ng.$interval
- *
- * @description
- * Cancels a task associated with the `promise`.
- *
- * @param {number} promise Promise returned by the `$interval` function.
- * @returns {boolean} Returns `true` if the task was successfully canceled.
- */
- interval.cancel = function(promise) {
- if (promise && promise.$$intervalId in intervals) {
- intervals[promise.$$intervalId].reject('canceled');
- clearInterval(promise.$$intervalId);
- delete intervals[promise.$$intervalId];
- return true;
- }
- return false;
- };
-
- return interval;
- }];
-}
-
-/**
- * @ngdoc object
- * @name ng.$locale
- *
- * @description
- * $locale service provides localization rules for various Angular components. As of right now the
- * only public api is:
- *
- * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
- */
-function $LocaleProvider(){
- this.$get = function() {
- return {
- id: 'en-us',
-
- NUMBER_FORMATS: {
- DECIMAL_SEP: '.',
- GROUP_SEP: ',',
- PATTERNS: [
- { // Decimal Pattern
- minInt: 1,
- minFrac: 0,
- maxFrac: 3,
- posPre: '',
- posSuf: '',
- negPre: '-',
- negSuf: '',
- gSize: 3,
- lgSize: 3
- },{ //Currency Pattern
- minInt: 1,
- minFrac: 2,
- maxFrac: 2,
- posPre: '\u00A4',
- posSuf: '',
- negPre: '(\u00A4',
- negSuf: ')',
- gSize: 3,
- lgSize: 3
- }
- ],
- CURRENCY_SYM: '$'
- },
-
- DATETIME_FORMATS: {
- MONTH:
- 'January,February,March,April,May,June,July,August,September,October,November,December'
- .split(','),
- SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
- DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
- SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
- AMPMS: ['AM','PM'],
- medium: 'MMM d, y h:mm:ss a',
- short: 'M/d/yy h:mm a',
- fullDate: 'EEEE, MMMM d, y',
- longDate: 'MMMM d, y',
- mediumDate: 'MMM d, y',
- shortDate: 'M/d/yy',
- mediumTime: 'h:mm:ss a',
- shortTime: 'h:mm a'
- },
-
- pluralCat: function(num) {
- if (num === 1) {
- return 'one';
- }
- return 'other';
- }
- };
- };
-}
-
-var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
- DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
-var $locationMinErr = minErr('$location');
-
-
-/**
- * Encode path using encodeUriSegment, ignoring forward slashes
- *
- * @param {string} path Path to encode
- * @returns {string}
- */
-function encodePath(path) {
- var segments = path.split('/'),
- i = segments.length;
-
- while (i--) {
- segments[i] = encodeUriSegment(segments[i]);
- }
-
- return segments.join('/');
-}
-
-function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
- var parsedUrl = urlResolve(absoluteUrl, appBase);
-
- locationObj.$$protocol = parsedUrl.protocol;
- locationObj.$$host = parsedUrl.hostname;
- locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
-}
-
-
-function parseAppUrl(relativeUrl, locationObj, appBase) {
- var prefixed = (relativeUrl.charAt(0) !== '/');
- if (prefixed) {
- relativeUrl = '/' + relativeUrl;
- }
- var match = urlResolve(relativeUrl, appBase);
- locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
- match.pathname.substring(1) : match.pathname);
- locationObj.$$search = parseKeyValue(match.search);
- locationObj.$$hash = decodeURIComponent(match.hash);
-
- // make sure path starts with '/';
- if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
- locationObj.$$path = '/' + locationObj.$$path;
- }
-}
-
-
-/**
- *
- * @param {string} begin
- * @param {string} whole
- * @returns {string} returns text from whole after begin or undefined if it does not begin with
- * expected string.
- */
-function beginsWith(begin, whole) {
- if (whole.indexOf(begin) === 0) {
- return whole.substr(begin.length);
- }
-}
-
-
-function stripHash(url) {
- var index = url.indexOf('#');
- return index == -1 ? url : url.substr(0, index);
-}
-
-
-function stripFile(url) {
- return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
-}
-
-/* return the server only (scheme://host:port) */
-function serverBase(url) {
- return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
-}
-
-
-/**
- * LocationHtml5Url represents an url
- * This object is exposed as $location service when HTML5 mode is enabled and supported
- *
- * @constructor
- * @param {string} appBase application base URL
- * @param {string} basePrefix url path prefix
- */
-function LocationHtml5Url(appBase, basePrefix) {
- this.$$html5 = true;
- basePrefix = basePrefix || '';
- var appBaseNoFile = stripFile(appBase);
- parseAbsoluteUrl(appBase, this, appBase);
-
-
- /**
- * Parse given html5 (regular) url string into properties
- * @param {string} newAbsoluteUrl HTML5 url
- * @private
- */
- this.$$parse = function(url) {
- var pathUrl = beginsWith(appBaseNoFile, url);
- if (!isString(pathUrl)) {
- throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
- appBaseNoFile);
- }
-
- parseAppUrl(pathUrl, this, appBase);
-
- if (!this.$$path) {
- this.$$path = '/';
- }
-
- this.$$compose();
- };
-
- /**
- * Compose url and update `absUrl` property
- * @private
- */
- this.$$compose = function() {
- var search = toKeyValue(this.$$search),
- hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
-
- this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
- this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
- };
-
- this.$$rewrite = function(url) {
- var appUrl, prevAppUrl;
-
- if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
- prevAppUrl = appUrl;
- if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
- return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
- } else {
- return appBase + prevAppUrl;
- }
- } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
- return appBaseNoFile + appUrl;
- } else if (appBaseNoFile == url + '/') {
- return appBaseNoFile;
- }
- };
-}
-
-
-/**
- * LocationHashbangUrl represents url
- * This object is exposed as $location service when developer doesn't opt into html5 mode.
- * It also serves as the base class for html5 mode fallback on legacy browsers.
- *
- * @constructor
- * @param {string} appBase application base URL
- * @param {string} hashPrefix hashbang prefix
- */
-function LocationHashbangUrl(appBase, hashPrefix) {
- var appBaseNoFile = stripFile(appBase);
-
- parseAbsoluteUrl(appBase, this, appBase);
-
-
- /**
- * Parse given hashbang url into properties
- * @param {string} url Hashbang url
- * @private
- */
- this.$$parse = function(url) {
- var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
- var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
- ? beginsWith(hashPrefix, withoutBaseUrl)
- : (this.$$html5)
- ? withoutBaseUrl
- : '';
-
- if (!isString(withoutHashUrl)) {
- throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
- hashPrefix);
- }
- parseAppUrl(withoutHashUrl, this, appBase);
-
- this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
-
- this.$$compose();
-
- /*
- * In Windows, on an anchor node on documents loaded from
- * the filesystem, the browser will return a pathname
- * prefixed with the drive name ('/C:/path') when a
- * pathname without a drive is set:
- * * a.setAttribute('href', '/foo')
- * * a.pathname === '/C:/foo' //true
- *
- * Inside of Angular, we're always using pathnames that
- * do not include drive names for routing.
- */
- function removeWindowsDriveName (path, url, base) {
- /*
- Matches paths for file protocol on windows,
- such as /C:/foo/bar, and captures only /foo/bar.
- */
- var windowsFilePathExp = /^\/?.*?:(\/.*)/;
-
- var firstPathSegmentMatch;
-
- //Get the relative path from the input URL.
- if (url.indexOf(base) === 0) {
- url = url.replace(base, '');
- }
-
- /*
- * The input URL intentionally contains a
- * first path segment that ends with a colon.
- */
- if (windowsFilePathExp.exec(url)) {
- return path;
- }
-
- firstPathSegmentMatch = windowsFilePathExp.exec(path);
- return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
- }
- };
-
- /**
- * Compose hashbang url and update `absUrl` property
- * @private
- */
- this.$$compose = function() {
- var search = toKeyValue(this.$$search),
- hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
-
- this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
- this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
- };
-
- this.$$rewrite = function(url) {
- if(stripHash(appBase) == stripHash(url)) {
- return url;
- }
- };
-}
-
-
-/**
- * LocationHashbangUrl represents url
- * This object is exposed as $location service when html5 history api is enabled but the browser
- * does not support it.
- *
- * @constructor
- * @param {string} appBase application base URL
- * @param {string} hashPrefix hashbang prefix
- */
-function LocationHashbangInHtml5Url(appBase, hashPrefix) {
- this.$$html5 = true;
- LocationHashbangUrl.apply(this, arguments);
-
- var appBaseNoFile = stripFile(appBase);
-
- this.$$rewrite = function(url) {
- var appUrl;
-
- if ( appBase == stripHash(url) ) {
- return url;
- } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
- return appBase + hashPrefix + appUrl;
- } else if ( appBaseNoFile === url + '/') {
- return appBaseNoFile;
- }
- };
-}
-
-
-LocationHashbangInHtml5Url.prototype =
- LocationHashbangUrl.prototype =
- LocationHtml5Url.prototype = {
-
- /**
- * Are we in html5 mode?
- * @private
- */
- $$html5: false,
-
- /**
- * Has any change been replacing ?
- * @private
- */
- $$replace: false,
-
- /**
- * @ngdoc method
- * @name ng.$location#absUrl
- * @methodOf ng.$location
- *
- * @description
- * This method is getter only.
- *
- * Return full url representation with all segments encoded according to rules specified in
- * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
- *
- * @return {string} full url
- */
- absUrl: locationGetter('$$absUrl'),
-
- /**
- * @ngdoc method
- * @name ng.$location#url
- * @methodOf ng.$location
- *
- * @description
- * This method is getter / setter.
- *
- * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
- *
- * Change path, search and hash, when called with parameter and return `$location`.
- *
- * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
- * @param {string=} replace The path that will be changed
- * @return {string} url
- */
- url: function(url, replace) {
- if (isUndefined(url))
- return this.$$url;
-
- var match = PATH_MATCH.exec(url);
- if (match[1]) this.path(decodeURIComponent(match[1]));
- if (match[2] || match[1]) this.search(match[3] || '');
- this.hash(match[5] || '', replace);
-
- return this;
- },
-
- /**
- * @ngdoc method
- * @name ng.$location#protocol
- * @methodOf ng.$location
- *
- * @description
- * This method is getter only.
- *
- * Return protocol of current url.
- *
- * @return {string} protocol of current url
- */
- protocol: locationGetter('$$protocol'),
-
- /**
- * @ngdoc method
- * @name ng.$location#host
- * @methodOf ng.$location
- *
- * @description
- * This method is getter only.
- *
- * Return host of current url.
- *
- * @return {string} host of current url.
- */
- host: locationGetter('$$host'),
-
- /**
- * @ngdoc method
- * @name ng.$location#port
- * @methodOf ng.$location
- *
- * @description
- * This method is getter only.
- *
- * Return port of current url.
- *
- * @return {Number} port
- */
- port: locationGetter('$$port'),
-
- /**
- * @ngdoc method
- * @name ng.$location#path
- * @methodOf ng.$location
- *
- * @description
- * This method is getter / setter.
- *
- * Return path of current url when called without any parameter.
- *
- * Change path when called with parameter and return `$location`.
- *
- * Note: Path should always begin with forward slash (/), this method will add the forward slash
- * if it is missing.
- *
- * @param {string=} path New path
- * @return {string} path
- */
- path: locationGetterSetter('$$path', function(path) {
- return path.charAt(0) == '/' ? path : '/' + path;
- }),
-
- /**
- * @ngdoc method
- * @name ng.$location#search
- * @methodOf ng.$location
- *
- * @description
- * This method is getter / setter.
- *
- * Return search part (as object) of current url when called without any parameter.
- *
- * Change search part when called with parameter and return `$location`.
- *
- * @param {string|Object.|Object.>} search New search params - string or
- * hash object. Hash object may contain an array of values, which will be decoded as duplicates in
- * the url.
- *
- * @param {(string|Array)=} paramValue If `search` is a string, then `paramValue` will override only a
- * single search parameter. If `paramValue` is an array, it will set the parameter as a
- * comma-separated value. If `paramValue` is `null`, the parameter will be deleted.
- *
- * @return {string} search
- */
- search: function(search, paramValue) {
- switch (arguments.length) {
- case 0:
- return this.$$search;
- case 1:
- if (isString(search)) {
- this.$$search = parseKeyValue(search);
- } else if (isObject(search)) {
- this.$$search = search;
- } else {
- throw $locationMinErr('isrcharg',
- 'The first argument of the `$location#search()` call must be a string or an object.');
- }
- break;
- default:
- if (isUndefined(paramValue) || paramValue === null) {
- delete this.$$search[search];
- } else {
- this.$$search[search] = paramValue;
- }
- }
-
- this.$$compose();
- return this;
- },
-
- /**
- * @ngdoc method
- * @name ng.$location#hash
- * @methodOf ng.$location
- *
- * @description
- * This method is getter / setter.
- *
- * Return hash fragment when called without any parameter.
- *
- * Change hash fragment when called with parameter and return `$location`.
- *
- * @param {string=} hash New hash fragment
- * @return {string} hash
- */
- hash: locationGetterSetter('$$hash', identity),
-
- /**
- * @ngdoc method
- * @name ng.$location#replace
- * @methodOf ng.$location
- *
- * @description
- * If called, all changes to $location during current `$digest` will be replacing current history
- * record, instead of adding new one.
- */
- replace: function() {
- this.$$replace = true;
- return this;
- }
-};
-
-function locationGetter(property) {
- return function() {
- return this[property];
- };
-}
-
-
-function locationGetterSetter(property, preprocess) {
- return function(value) {
- if (isUndefined(value))
- return this[property];
-
- this[property] = preprocess(value);
- this.$$compose();
-
- return this;
- };
-}
-
-
-/**
- * @ngdoc object
- * @name ng.$location
- *
- * @requires $browser
- * @requires $sniffer
- * @requires $rootElement
- *
- * @description
- * The $location service parses the URL in the browser address bar (based on the
- * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
- * available to your application. Changes to the URL in the address bar are reflected into
- * $location service and changes to $location are reflected into the browser address bar.
- *
- * **The $location service:**
- *
- * - Exposes the current URL in the browser address bar, so you can
- * - Watch and observe the URL.
- * - Change the URL.
- * - Synchronizes the URL with the browser when the user
- * - Changes the address bar.
- * - Clicks the back or forward button (or clicks a History link).
- * - Clicks on a link.
- * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
- *
- * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
- * Services: Using $location}
- */
-
-/**
- * @ngdoc object
- * @name ng.$locationProvider
- * @description
- * Use the `$locationProvider` to configure how the application deep linking paths are stored.
- */
-function $LocationProvider(){
- var hashPrefix = '',
- html5Mode = false;
-
- /**
- * @ngdoc property
- * @name ng.$locationProvider#hashPrefix
- * @methodOf ng.$locationProvider
- * @description
- * @param {string=} prefix Prefix for hash part (containing path and search)
- * @returns {*} current value if used as getter or itself (chaining) if used as setter
- */
- this.hashPrefix = function(prefix) {
- if (isDefined(prefix)) {
- hashPrefix = prefix;
- return this;
- } else {
- return hashPrefix;
- }
- };
-
- /**
- * @ngdoc property
- * @name ng.$locationProvider#html5Mode
- * @methodOf ng.$locationProvider
- * @description
- * @param {boolean=} mode Use HTML5 strategy if available.
- * @returns {*} current value if used as getter or itself (chaining) if used as setter
- */
- this.html5Mode = function(mode) {
- if (isDefined(mode)) {
- html5Mode = mode;
- return this;
- } else {
- return html5Mode;
- }
- };
-
- /**
- * @ngdoc event
- * @name ng.$location#$locationChangeStart
- * @eventOf ng.$location
- * @eventType broadcast on root scope
- * @description
- * Broadcasted before a URL will change. This change can be prevented by calling
- * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
- * details about event object. Upon successful change
- * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
- *
- * @param {Object} angularEvent Synthetic event object.
- * @param {string} newUrl New URL
- * @param {string=} oldUrl URL that was before it was changed.
- */
-
- /**
- * @ngdoc event
- * @name ng.$location#$locationChangeSuccess
- * @eventOf ng.$location
- * @eventType broadcast on root scope
- * @description
- * Broadcasted after a URL was changed.
- *
- * @param {Object} angularEvent Synthetic event object.
- * @param {string} newUrl New URL
- * @param {string=} oldUrl URL that was before it was changed.
- */
-
- this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
- function( $rootScope, $browser, $sniffer, $rootElement) {
- var $location,
- LocationMode,
- baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
- initialUrl = $browser.url(),
- appBase;
-
- if (html5Mode) {
- appBase = serverBase(initialUrl) + (baseHref || '/');
- LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
- } else {
- appBase = stripHash(initialUrl);
- LocationMode = LocationHashbangUrl;
- }
- $location = new LocationMode(appBase, '#' + hashPrefix);
- $location.$$parse($location.$$rewrite(initialUrl));
-
- $rootElement.on('click', function(event) {
- // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
- // currently we open nice url link and redirect then
-
- if (event.ctrlKey || event.metaKey || event.which == 2) return;
-
- var elm = jqLite(event.target);
-
- // traverse the DOM up to find first A tag
- while (lowercase(elm[0].nodeName) !== 'a') {
- // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
- if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
- }
-
- var absHref = elm.prop('href');
-
- if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
- // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
- // an animation.
- absHref = urlResolve(absHref.animVal).href;
- }
-
- var rewrittenUrl = $location.$$rewrite(absHref);
-
- if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
- event.preventDefault();
- if (rewrittenUrl != $browser.url()) {
- // update location manually
- $location.$$parse(rewrittenUrl);
- $rootScope.$apply();
- // hack to work around FF6 bug 684208 when scenario runner clicks on links
- window.angular['ff-684208-preventDefault'] = true;
- }
- }
- });
-
-
- // rewrite hashbang url <> html5 url
- if ($location.absUrl() != initialUrl) {
- $browser.url($location.absUrl(), true);
- }
-
- // update $location when $browser url changes
- $browser.onUrlChange(function(newUrl) {
- if ($location.absUrl() != newUrl) {
- $rootScope.$evalAsync(function() {
- var oldUrl = $location.absUrl();
-
- $location.$$parse(newUrl);
- if ($rootScope.$broadcast('$locationChangeStart', newUrl,
- oldUrl).defaultPrevented) {
- $location.$$parse(oldUrl);
- $browser.url(oldUrl);
- } else {
- afterLocationChange(oldUrl);
- }
- });
- if (!$rootScope.$$phase) $rootScope.$digest();
- }
- });
-
- // update browser
- var changeCounter = 0;
- $rootScope.$watch(function $locationWatch() {
- var oldUrl = $browser.url();
- var currentReplace = $location.$$replace;
-
- if (!changeCounter || oldUrl != $location.absUrl()) {
- changeCounter++;
- $rootScope.$evalAsync(function() {
- if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
- defaultPrevented) {
- $location.$$parse(oldUrl);
- } else {
- $browser.url($location.absUrl(), currentReplace);
- afterLocationChange(oldUrl);
- }
- });
- }
- $location.$$replace = false;
-
- return changeCounter;
- });
-
- return $location;
-
- function afterLocationChange(oldUrl) {
- $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
- }
-}];
-}
-
-/**
- * @ngdoc object
- * @name ng.$log
- * @requires $window
- *
- * @description
- * Simple service for logging. Default implementation safely writes the message
- * into the browser's console (if present).
- *
- * The main purpose of this service is to simplify debugging and troubleshooting.
- *
- * The default is to log `debug` messages. You can use
- * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
- *
- * @example
-
-
- function LogCtrl($scope, $log) {
- $scope.$log = $log;
- $scope.message = 'Hello World!';
- }
-
-
-
-
Reload this page with open console, enter text and hit the log button...
- Message:
-
-
-
-
-
-
-
-
- */
-
-/**
- * @ngdoc object
- * @name ng.$logProvider
- * @description
- * Use the `$logProvider` to configure how the application logs messages
- */
-function $LogProvider(){
- var debug = true,
- self = this;
-
- /**
- * @ngdoc property
- * @name ng.$logProvider#debugEnabled
- * @methodOf ng.$logProvider
- * @description
- * @param {string=} flag enable or disable debug level messages
- * @returns {*} current value if used as getter or itself (chaining) if used as setter
- */
- this.debugEnabled = function(flag) {
- if (isDefined(flag)) {
- debug = flag;
- return this;
- } else {
- return debug;
- }
- };
-
- this.$get = ['$window', function($window){
- return {
- /**
- * @ngdoc method
- * @name ng.$log#log
- * @methodOf ng.$log
- *
- * @description
- * Write a log message
- */
- log: consoleLog('log'),
-
- /**
- * @ngdoc method
- * @name ng.$log#info
- * @methodOf ng.$log
- *
- * @description
- * Write an information message
- */
- info: consoleLog('info'),
-
- /**
- * @ngdoc method
- * @name ng.$log#warn
- * @methodOf ng.$log
- *
- * @description
- * Write a warning message
- */
- warn: consoleLog('warn'),
-
- /**
- * @ngdoc method
- * @name ng.$log#error
- * @methodOf ng.$log
- *
- * @description
- * Write an error message
- */
- error: consoleLog('error'),
-
- /**
- * @ngdoc method
- * @name ng.$log#debug
- * @methodOf ng.$log
- *
- * @description
- * Write a debug message
- */
- debug: (function () {
- var fn = consoleLog('debug');
-
- return function() {
- if (debug) {
- fn.apply(self, arguments);
- }
- };
- }())
- };
-
- function formatError(arg) {
- if (arg instanceof Error) {
- if (arg.stack) {
- arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
- ? 'Error: ' + arg.message + '\n' + arg.stack
- : arg.stack;
- } else if (arg.sourceURL) {
- arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
- }
- }
- return arg;
- }
-
- function consoleLog(type) {
- var console = $window.console || {},
- logFn = console[type] || console.log || noop,
- hasApply = false;
-
- // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
- // The reason behind this is that console.log has type "object" in IE8...
- try {
- hasApply = !! logFn.apply;
- } catch (e) {}
-
- if (hasApply) {
- return function() {
- var args = [];
- forEach(arguments, function(arg) {
- args.push(formatError(arg));
- });
- return logFn.apply(console, args);
- };
- }
-
- // we are IE which either doesn't have window.console => this is noop and we do nothing,
- // or we are IE where console.log doesn't have apply so we log at least first 2 args
- return function(arg1, arg2) {
- logFn(arg1, arg2 == null ? '' : arg2);
- };
- }
- }];
-}
-
-var $parseMinErr = minErr('$parse');
-var promiseWarningCache = {};
-var promiseWarning;
-
-// Sandboxing Angular Expressions
-// ------------------------------
-// Angular expressions are generally considered safe because these expressions only have direct
-// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
-// obtaining a reference to native JS functions such as the Function constructor.
-//
-// As an example, consider the following Angular expression:
-//
-// {}.toString.constructor(alert("evil JS code"))
-//
-// We want to prevent this type of access. For the sake of performance, during the lexing phase we
-// disallow any "dotted" access to any member named "constructor".
-//
-// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor
-// while evaluating the expression, which is a stronger but more expensive test. Since reflective
-// calls are expensive anyway, this is not such a big deal compared to static dereferencing.
-//
-// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
-// against the expression language, but not to prevent exploits that were enabled by exposing
-// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
-// practice and therefore we are not even trying to protect against interaction with an object
-// explicitly exposed in this way.
-//
-// A developer could foil the name check by aliasing the Function constructor under a different
-// name on the scope.
-//
-// In general, it is not possible to access a Window object from an angular expression unless a
-// window or some DOM object that has a reference to window is published onto a Scope.
-
-function ensureSafeMemberName(name, fullExpression) {
- if (name === "constructor") {
- throw $parseMinErr('isecfld',
- 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
- fullExpression);
- }
- return name;
-}
-
-function ensureSafeObject(obj, fullExpression) {
- // nifty check if obj is Function that is fast and works across iframes and other contexts
- if (obj) {
- if (obj.constructor === obj) {
- throw $parseMinErr('isecfn',
- 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
- fullExpression);
- } else if (// isWindow(obj)
- obj.document && obj.location && obj.alert && obj.setInterval) {
- throw $parseMinErr('isecwindow',
- 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
- fullExpression);
- } else if (// isElement(obj)
- obj.children && (obj.nodeName || (obj.on && obj.find))) {
- throw $parseMinErr('isecdom',
- 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
- fullExpression);
- }
- }
- return obj;
-}
-
-var OPERATORS = {
- /* jshint bitwise : false */
- 'null':function(){return null;},
- 'true':function(){return true;},
- 'false':function(){return false;},
- undefined:noop,
- '+':function(self, locals, a,b){
- a=a(self, locals); b=b(self, locals);
- if (isDefined(a)) {
- if (isDefined(b)) {
- return a + b;
- }
- return a;
- }
- return isDefined(b)?b:undefined;},
- '-':function(self, locals, a,b){
- a=a(self, locals); b=b(self, locals);
- return (isDefined(a)?a:0)-(isDefined(b)?b:0);
- },
- '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
- '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
- '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
- '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
- '=':noop,
- '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
- '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
- '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
- '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
- '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
- '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
- '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
- '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
- '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
- '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
-// '|':function(self, locals, a,b){return a|b;},
- '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
- '!':function(self, locals, a){return !a(self, locals);}
-};
-/* jshint bitwise: true */
-var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
-
-
-/////////////////////////////////////////
-
-
-/**
- * @constructor
- */
-var Lexer = function (options) {
- this.options = options;
-};
-
-Lexer.prototype = {
- constructor: Lexer,
-
- lex: function (text) {
- this.text = text;
-
- this.index = 0;
- this.ch = undefined;
- this.lastCh = ':'; // can start regexp
-
- this.tokens = [];
-
- var token;
- var json = [];
-
- while (this.index < this.text.length) {
- this.ch = this.text.charAt(this.index);
- if (this.is('"\'')) {
- this.readString(this.ch);
- } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
- this.readNumber();
- } else if (this.isIdent(this.ch)) {
- this.readIdent();
- // identifiers can only be if the preceding char was a { or ,
- if (this.was('{,') && json[0] === '{' &&
- (token = this.tokens[this.tokens.length - 1])) {
- token.json = token.text.indexOf('.') === -1;
- }
- } else if (this.is('(){}[].,;:?')) {
- this.tokens.push({
- index: this.index,
- text: this.ch,
- json: (this.was(':[,') && this.is('{[')) || this.is('}]:,')
- });
- if (this.is('{[')) json.unshift(this.ch);
- if (this.is('}]')) json.shift();
- this.index++;
- } else if (this.isWhitespace(this.ch)) {
- this.index++;
- continue;
- } else {
- var ch2 = this.ch + this.peek();
- var ch3 = ch2 + this.peek(2);
- var fn = OPERATORS[this.ch];
- var fn2 = OPERATORS[ch2];
- var fn3 = OPERATORS[ch3];
- if (fn3) {
- this.tokens.push({index: this.index, text: ch3, fn: fn3});
- this.index += 3;
- } else if (fn2) {
- this.tokens.push({index: this.index, text: ch2, fn: fn2});
- this.index += 2;
- } else if (fn) {
- this.tokens.push({
- index: this.index,
- text: this.ch,
- fn: fn,
- json: (this.was('[,:') && this.is('+-'))
- });
- this.index += 1;
- } else {
- this.throwError('Unexpected next character ', this.index, this.index + 1);
- }
- }
- this.lastCh = this.ch;
- }
- return this.tokens;
- },
-
- is: function(chars) {
- return chars.indexOf(this.ch) !== -1;
- },
-
- was: function(chars) {
- return chars.indexOf(this.lastCh) !== -1;
- },
-
- peek: function(i) {
- var num = i || 1;
- return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
- },
-
- isNumber: function(ch) {
- return ('0' <= ch && ch <= '9');
- },
-
- isWhitespace: function(ch) {
- // IE treats non-breaking space as \u00A0
- return (ch === ' ' || ch === '\r' || ch === '\t' ||
- ch === '\n' || ch === '\v' || ch === '\u00A0');
- },
-
- isIdent: function(ch) {
- return ('a' <= ch && ch <= 'z' ||
- 'A' <= ch && ch <= 'Z' ||
- '_' === ch || ch === '$');
- },
-
- isExpOperator: function(ch) {
- return (ch === '-' || ch === '+' || this.isNumber(ch));
- },
-
- throwError: function(error, start, end) {
- end = end || this.index;
- var colStr = (isDefined(start)
- ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
- : ' ' + end);
- throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
- error, colStr, this.text);
- },
-
- readNumber: function() {
- var number = '';
- var start = this.index;
- while (this.index < this.text.length) {
- var ch = lowercase(this.text.charAt(this.index));
- if (ch == '.' || this.isNumber(ch)) {
- number += ch;
- } else {
- var peekCh = this.peek();
- if (ch == 'e' && this.isExpOperator(peekCh)) {
- number += ch;
- } else if (this.isExpOperator(ch) &&
- peekCh && this.isNumber(peekCh) &&
- number.charAt(number.length - 1) == 'e') {
- number += ch;
- } else if (this.isExpOperator(ch) &&
- (!peekCh || !this.isNumber(peekCh)) &&
- number.charAt(number.length - 1) == 'e') {
- this.throwError('Invalid exponent');
- } else {
- break;
- }
- }
- this.index++;
- }
- number = 1 * number;
- this.tokens.push({
- index: start,
- text: number,
- json: true,
- fn: function() { return number; }
- });
- },
-
- readIdent: function() {
- var parser = this;
-
- var ident = '';
- var start = this.index;
-
- var lastDot, peekIndex, methodName, ch;
-
- while (this.index < this.text.length) {
- ch = this.text.charAt(this.index);
- if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
- if (ch === '.') lastDot = this.index;
- ident += ch;
- } else {
- break;
- }
- this.index++;
- }
-
- //check if this is not a method invocation and if it is back out to last dot
- if (lastDot) {
- peekIndex = this.index;
- while (peekIndex < this.text.length) {
- ch = this.text.charAt(peekIndex);
- if (ch === '(') {
- methodName = ident.substr(lastDot - start + 1);
- ident = ident.substr(0, lastDot - start);
- this.index = peekIndex;
- break;
- }
- if (this.isWhitespace(ch)) {
- peekIndex++;
- } else {
- break;
- }
- }
- }
-
-
- var token = {
- index: start,
- text: ident
- };
-
- // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
- if (OPERATORS.hasOwnProperty(ident)) {
- token.fn = OPERATORS[ident];
- token.json = OPERATORS[ident];
- } else {
- var getter = getterFn(ident, this.options, this.text);
- token.fn = extend(function(self, locals) {
- return (getter(self, locals));
- }, {
- assign: function(self, value) {
- return setter(self, ident, value, parser.text, parser.options);
- }
- });
- }
-
- this.tokens.push(token);
-
- if (methodName) {
- this.tokens.push({
- index:lastDot,
- text: '.',
- json: false
- });
- this.tokens.push({
- index: lastDot + 1,
- text: methodName,
- json: false
- });
- }
- },
-
- readString: function(quote) {
- var start = this.index;
- this.index++;
- var string = '';
- var rawString = quote;
- var escape = false;
- while (this.index < this.text.length) {
- var ch = this.text.charAt(this.index);
- rawString += ch;
- if (escape) {
- if (ch === 'u') {
- var hex = this.text.substring(this.index + 1, this.index + 5);
- if (!hex.match(/[\da-f]{4}/i))
- this.throwError('Invalid unicode escape [\\u' + hex + ']');
- this.index += 4;
- string += String.fromCharCode(parseInt(hex, 16));
- } else {
- var rep = ESCAPE[ch];
- if (rep) {
- string += rep;
- } else {
- string += ch;
- }
- }
- escape = false;
- } else if (ch === '\\') {
- escape = true;
- } else if (ch === quote) {
- this.index++;
- this.tokens.push({
- index: start,
- text: rawString,
- string: string,
- json: true,
- fn: function() { return string; }
- });
- return;
- } else {
- string += ch;
- }
- this.index++;
- }
- this.throwError('Unterminated quote', start);
- }
-};
-
-
-/**
- * @constructor
- */
-var Parser = function (lexer, $filter, options) {
- this.lexer = lexer;
- this.$filter = $filter;
- this.options = options;
-};
-
-Parser.ZERO = function () { return 0; };
-
-Parser.prototype = {
- constructor: Parser,
-
- parse: function (text, json) {
- this.text = text;
-
- //TODO(i): strip all the obsolte json stuff from this file
- this.json = json;
-
- this.tokens = this.lexer.lex(text);
-
- if (json) {
- // The extra level of aliasing is here, just in case the lexer misses something, so that
- // we prevent any accidental execution in JSON.
- this.assignment = this.logicalOR;
-
- this.functionCall =
- this.fieldAccess =
- this.objectIndex =
- this.filterChain = function() {
- this.throwError('is not valid json', {text: text, index: 0});
- };
- }
-
- var value = json ? this.primary() : this.statements();
-
- if (this.tokens.length !== 0) {
- this.throwError('is an unexpected token', this.tokens[0]);
- }
-
- value.literal = !!value.literal;
- value.constant = !!value.constant;
-
- return value;
- },
-
- primary: function () {
- var primary;
- if (this.expect('(')) {
- primary = this.filterChain();
- this.consume(')');
- } else if (this.expect('[')) {
- primary = this.arrayDeclaration();
- } else if (this.expect('{')) {
- primary = this.object();
- } else {
- var token = this.expect();
- primary = token.fn;
- if (!primary) {
- this.throwError('not a primary expression', token);
- }
- if (token.json) {
- primary.constant = true;
- primary.literal = true;
- }
- }
-
- var next, context;
- while ((next = this.expect('(', '[', '.'))) {
- if (next.text === '(') {
- primary = this.functionCall(primary, context);
- context = null;
- } else if (next.text === '[') {
- context = primary;
- primary = this.objectIndex(primary);
- } else if (next.text === '.') {
- context = primary;
- primary = this.fieldAccess(primary);
- } else {
- this.throwError('IMPOSSIBLE');
- }
- }
- return primary;
- },
-
- throwError: function(msg, token) {
- throw $parseMinErr('syntax',
- 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
- token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
- },
-
- peekToken: function() {
- if (this.tokens.length === 0)
- throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
- return this.tokens[0];
- },
-
- peek: function(e1, e2, e3, e4) {
- if (this.tokens.length > 0) {
- var token = this.tokens[0];
- var t = token.text;
- if (t === e1 || t === e2 || t === e3 || t === e4 ||
- (!e1 && !e2 && !e3 && !e4)) {
- return token;
- }
- }
- return false;
- },
-
- expect: function(e1, e2, e3, e4){
- var token = this.peek(e1, e2, e3, e4);
- if (token) {
- if (this.json && !token.json) {
- this.throwError('is not valid json', token);
- }
- this.tokens.shift();
- return token;
- }
- return false;
- },
-
- consume: function(e1){
- if (!this.expect(e1)) {
- this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
- }
- },
-
- unaryFn: function(fn, right) {
- return extend(function(self, locals) {
- return fn(self, locals, right);
- }, {
- constant:right.constant
- });
- },
-
- ternaryFn: function(left, middle, right){
- return extend(function(self, locals){
- return left(self, locals) ? middle(self, locals) : right(self, locals);
- }, {
- constant: left.constant && middle.constant && right.constant
- });
- },
-
- binaryFn: function(left, fn, right) {
- return extend(function(self, locals) {
- return fn(self, locals, left, right);
- }, {
- constant:left.constant && right.constant
- });
- },
-
- statements: function() {
- var statements = [];
- while (true) {
- if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
- statements.push(this.filterChain());
- if (!this.expect(';')) {
- // optimize for the common case where there is only one statement.
- // TODO(size): maybe we should not support multiple statements?
- return (statements.length === 1)
- ? statements[0]
- : function(self, locals) {
- var value;
- for (var i = 0; i < statements.length; i++) {
- var statement = statements[i];
- if (statement) {
- value = statement(self, locals);
- }
- }
- return value;
- };
- }
- }
- },
-
- filterChain: function() {
- var left = this.expression();
- var token;
- while (true) {
- if ((token = this.expect('|'))) {
- left = this.binaryFn(left, token.fn, this.filter());
- } else {
- return left;
- }
- }
- },
-
- filter: function() {
- var token = this.expect();
- var fn = this.$filter(token.text);
- var argsFn = [];
- while (true) {
- if ((token = this.expect(':'))) {
- argsFn.push(this.expression());
- } else {
- var fnInvoke = function(self, locals, input) {
- var args = [input];
- for (var i = 0; i < argsFn.length; i++) {
- args.push(argsFn[i](self, locals));
- }
- return fn.apply(self, args);
- };
- return function() {
- return fnInvoke;
- };
- }
- }
- },
-
- expression: function() {
- return this.assignment();
- },
-
- assignment: function() {
- var left = this.ternary();
- var right;
- var token;
- if ((token = this.expect('='))) {
- if (!left.assign) {
- this.throwError('implies assignment but [' +
- this.text.substring(0, token.index) + '] can not be assigned to', token);
- }
- right = this.ternary();
- return function(scope, locals) {
- return left.assign(scope, right(scope, locals), locals);
- };
- }
- return left;
- },
-
- ternary: function() {
- var left = this.logicalOR();
- var middle;
- var token;
- if ((token = this.expect('?'))) {
- middle = this.ternary();
- if ((token = this.expect(':'))) {
- return this.ternaryFn(left, middle, this.ternary());
- } else {
- this.throwError('expected :', token);
- }
- } else {
- return left;
- }
- },
-
- logicalOR: function() {
- var left = this.logicalAND();
- var token;
- while (true) {
- if ((token = this.expect('||'))) {
- left = this.binaryFn(left, token.fn, this.logicalAND());
- } else {
- return left;
- }
- }
- },
-
- logicalAND: function() {
- var left = this.equality();
- var token;
- if ((token = this.expect('&&'))) {
- left = this.binaryFn(left, token.fn, this.logicalAND());
- }
- return left;
- },
-
- equality: function() {
- var left = this.relational();
- var token;
- if ((token = this.expect('==','!=','===','!=='))) {
- left = this.binaryFn(left, token.fn, this.equality());
- }
- return left;
- },
-
- relational: function() {
- var left = this.additive();
- var token;
- if ((token = this.expect('<', '>', '<=', '>='))) {
- left = this.binaryFn(left, token.fn, this.relational());
- }
- return left;
- },
-
- additive: function() {
- var left = this.multiplicative();
- var token;
- while ((token = this.expect('+','-'))) {
- left = this.binaryFn(left, token.fn, this.multiplicative());
- }
- return left;
- },
-
- multiplicative: function() {
- var left = this.unary();
- var token;
- while ((token = this.expect('*','/','%'))) {
- left = this.binaryFn(left, token.fn, this.unary());
- }
- return left;
- },
-
- unary: function() {
- var token;
- if (this.expect('+')) {
- return this.primary();
- } else if ((token = this.expect('-'))) {
- return this.binaryFn(Parser.ZERO, token.fn, this.unary());
- } else if ((token = this.expect('!'))) {
- return this.unaryFn(token.fn, this.unary());
- } else {
- return this.primary();
- }
- },
-
- fieldAccess: function(object) {
- var parser = this;
- var field = this.expect().text;
- var getter = getterFn(field, this.options, this.text);
-
- return extend(function(scope, locals, self) {
- return getter(self || object(scope, locals), locals);
- }, {
- assign: function(scope, value, locals) {
- return setter(object(scope, locals), field, value, parser.text, parser.options);
- }
- });
- },
-
- objectIndex: function(obj) {
- var parser = this;
-
- var indexFn = this.expression();
- this.consume(']');
-
- return extend(function(self, locals) {
- var o = obj(self, locals),
- i = indexFn(self, locals),
- v, p;
-
- if (!o) return undefined;
- v = ensureSafeObject(o[i], parser.text);
- if (v && v.then && parser.options.unwrapPromises) {
- p = v;
- if (!('$$v' in v)) {
- p.$$v = undefined;
- p.then(function(val) { p.$$v = val; });
- }
- v = v.$$v;
- }
- return v;
- }, {
- assign: function(self, value, locals) {
- var key = indexFn(self, locals);
- // prevent overwriting of Function.constructor which would break ensureSafeObject check
- var safe = ensureSafeObject(obj(self, locals), parser.text);
- return safe[key] = value;
- }
- });
- },
-
- functionCall: function(fn, contextGetter) {
- var argsFn = [];
- if (this.peekToken().text !== ')') {
- do {
- argsFn.push(this.expression());
- } while (this.expect(','));
- }
- this.consume(')');
-
- var parser = this;
-
- return function(scope, locals) {
- var args = [];
- var context = contextGetter ? contextGetter(scope, locals) : scope;
-
- for (var i = 0; i < argsFn.length; i++) {
- args.push(argsFn[i](scope, locals));
- }
- var fnPtr = fn(scope, locals, context) || noop;
-
- ensureSafeObject(context, parser.text);
- ensureSafeObject(fnPtr, parser.text);
-
- // IE stupidity! (IE doesn't have apply for some native functions)
- var v = fnPtr.apply
- ? fnPtr.apply(context, args)
- : fnPtr(args[0], args[1], args[2], args[3], args[4]);
-
- return ensureSafeObject(v, parser.text);
- };
- },
-
- // This is used with json array declaration
- arrayDeclaration: function () {
- var elementFns = [];
- var allConstant = true;
- if (this.peekToken().text !== ']') {
- do {
- var elementFn = this.expression();
- elementFns.push(elementFn);
- if (!elementFn.constant) {
- allConstant = false;
- }
- } while (this.expect(','));
- }
- this.consume(']');
-
- return extend(function(self, locals) {
- var array = [];
- for (var i = 0; i < elementFns.length; i++) {
- array.push(elementFns[i](self, locals));
- }
- return array;
- }, {
- literal: true,
- constant: allConstant
- });
- },
-
- object: function () {
- var keyValues = [];
- var allConstant = true;
- if (this.peekToken().text !== '}') {
- do {
- var token = this.expect(),
- key = token.string || token.text;
- this.consume(':');
- var value = this.expression();
- keyValues.push({key: key, value: value});
- if (!value.constant) {
- allConstant = false;
- }
- } while (this.expect(','));
- }
- this.consume('}');
-
- return extend(function(self, locals) {
- var object = {};
- for (var i = 0; i < keyValues.length; i++) {
- var keyValue = keyValues[i];
- object[keyValue.key] = keyValue.value(self, locals);
- }
- return object;
- }, {
- literal: true,
- constant: allConstant
- });
- }
-};
-
-
-//////////////////////////////////////////////////
-// Parser helper functions
-//////////////////////////////////////////////////
-
-function setter(obj, path, setValue, fullExp, options) {
- //needed?
- options = options || {};
-
- var element = path.split('.'), key;
- for (var i = 0; element.length > 1; i++) {
- key = ensureSafeMemberName(element.shift(), fullExp);
- var propertyObj = obj[key];
- if (!propertyObj) {
- propertyObj = {};
- obj[key] = propertyObj;
- }
- obj = propertyObj;
- if (obj.then && options.unwrapPromises) {
- promiseWarning(fullExp);
- if (!("$$v" in obj)) {
- (function(promise) {
- promise.then(function(val) { promise.$$v = val; }); }
- )(obj);
- }
- if (obj.$$v === undefined) {
- obj.$$v = {};
- }
- obj = obj.$$v;
- }
- }
- key = ensureSafeMemberName(element.shift(), fullExp);
- obj[key] = setValue;
- return setValue;
-}
-
-var getterFnCache = {};
-
-/**
- * Implementation of the "Black Hole" variant from:
- * - http://jsperf.com/angularjs-parse-getter/4
- * - http://jsperf.com/path-evaluation-simplified/7
- */
-function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
- ensureSafeMemberName(key0, fullExp);
- ensureSafeMemberName(key1, fullExp);
- ensureSafeMemberName(key2, fullExp);
- ensureSafeMemberName(key3, fullExp);
- ensureSafeMemberName(key4, fullExp);
-
- return !options.unwrapPromises
- ? function cspSafeGetter(scope, locals) {
- var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
-
- if (pathVal == null) return pathVal;
- pathVal = pathVal[key0];
-
- if (!key1) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key1];
-
- if (!key2) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key2];
-
- if (!key3) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key3];
-
- if (!key4) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key4];
-
- return pathVal;
- }
- : function cspSafePromiseEnabledGetter(scope, locals) {
- var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
- promise;
-
- if (pathVal == null) return pathVal;
-
- pathVal = pathVal[key0];
- if (pathVal && pathVal.then) {
- promiseWarning(fullExp);
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
-
- if (!key1) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key1];
- if (pathVal && pathVal.then) {
- promiseWarning(fullExp);
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
-
- if (!key2) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key2];
- if (pathVal && pathVal.then) {
- promiseWarning(fullExp);
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
-
- if (!key3) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key3];
- if (pathVal && pathVal.then) {
- promiseWarning(fullExp);
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
-
- if (!key4) return pathVal;
- if (pathVal == null) return undefined;
- pathVal = pathVal[key4];
- if (pathVal && pathVal.then) {
- promiseWarning(fullExp);
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
- return pathVal;
- };
-}
-
-function simpleGetterFn1(key0, fullExp) {
- ensureSafeMemberName(key0, fullExp);
-
- return function simpleGetterFn1(scope, locals) {
- if (scope == null) return undefined;
- return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
- };
-}
-
-function simpleGetterFn2(key0, key1, fullExp) {
- ensureSafeMemberName(key0, fullExp);
- ensureSafeMemberName(key1, fullExp);
-
- return function simpleGetterFn2(scope, locals) {
- if (scope == null) return undefined;
- scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
- return scope == null ? undefined : scope[key1];
- };
-}
-
-function getterFn(path, options, fullExp) {
- // Check whether the cache has this getter already.
- // We can use hasOwnProperty directly on the cache because we ensure,
- // see below, that the cache never stores a path called 'hasOwnProperty'
- if (getterFnCache.hasOwnProperty(path)) {
- return getterFnCache[path];
- }
-
- var pathKeys = path.split('.'),
- pathKeysLength = pathKeys.length,
- fn;
-
- // When we have only 1 or 2 tokens, use optimized special case closures.
- // http://jsperf.com/angularjs-parse-getter/6
- if (!options.unwrapPromises && pathKeysLength === 1) {
- fn = simpleGetterFn1(pathKeys[0], fullExp);
- } else if (!options.unwrapPromises && pathKeysLength === 2) {
- fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp);
- } else if (options.csp) {
- if (pathKeysLength < 6) {
- fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
- options);
- } else {
- fn = function(scope, locals) {
- var i = 0, val;
- do {
- val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
- pathKeys[i++], fullExp, options)(scope, locals);
-
- locals = undefined; // clear after first iteration
- scope = val;
- } while (i < pathKeysLength);
- return val;
- };
- }
- } else {
- var code = 'var p;\n';
- forEach(pathKeys, function(key, index) {
- ensureSafeMemberName(key, fullExp);
- code += 'if(s == null) return undefined;\n' +
- 's='+ (index
- // we simply dereference 's' on any .dot notation
- ? 's'
- // but if we are first then we check locals first, and if so read it first
- : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
- (options.unwrapPromises
- ? 'if (s && s.then) {\n' +
- ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
- ' if (!("$$v" in s)) {\n' +
- ' p=s;\n' +
- ' p.$$v = undefined;\n' +
- ' p.then(function(v) {p.$$v=v;});\n' +
- '}\n' +
- ' s=s.$$v\n' +
- '}\n'
- : '');
- });
- code += 'return s;';
-
- /* jshint -W054 */
- var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
- /* jshint +W054 */
- evaledFnGetter.toString = valueFn(code);
- fn = options.unwrapPromises ? function(scope, locals) {
- return evaledFnGetter(scope, locals, promiseWarning);
- } : evaledFnGetter;
- }
-
- // Only cache the value if it's not going to mess up the cache object
- // This is more performant that using Object.prototype.hasOwnProperty.call
- if (path !== 'hasOwnProperty') {
- getterFnCache[path] = fn;
- }
- return fn;
-}
-
-///////////////////////////////////
-
-/**
- * @ngdoc function
- * @name ng.$parse
- * @function
- *
- * @description
- *
- * Converts Angular {@link guide/expression expression} into a function.
- *
- *
- *
- *
- * @param {string} expression String expression to compile.
- * @returns {function(context, locals)} a function which represents the compiled expression:
- *
- * * `context` – `{object}` – an object against which any expressions embedded in the strings
- * are evaluated against (typically a scope object).
- * * `locals` – `{object=}` – local variables context object, useful for overriding values in
- * `context`.
- *
- * The returned function also has the following properties:
- * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
- * literal.
- * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
- * constant literals.
- * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
- * set to a function to change its value on the given context.
- *
- */
-
-
-/**
- * @ngdoc object
- * @name ng.$parseProvider
- * @function
- *
- * @description
- * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
- * service.
- */
-function $ParseProvider() {
- var cache = {};
-
- var $parseOptions = {
- csp: false,
- unwrapPromises: false,
- logPromiseWarnings: true
- };
-
-
- /**
- * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
- *
- * @ngdoc method
- * @name ng.$parseProvider#unwrapPromises
- * @methodOf ng.$parseProvider
- * @description
- *
- * **This feature is deprecated, see deprecation notes below for more info**
- *
- * If set to true (default is false), $parse will unwrap promises automatically when a promise is
- * found at any part of the expression. In other words, if set to true, the expression will always
- * result in a non-promise value.
- *
- * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
- * the fulfillment value is used in place of the promise while evaluating the expression.
- *
- * **Deprecation notice**
- *
- * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
- * dichotomy between data access in templates (accessed as raw values) and controller code
- * (accessed as promises).
- *
- * In most code we ended up resolving promises manually in controllers anyway and thus unifying
- * the model access there.
- *
- * Other downsides of automatic promise unwrapping:
- *
- * - when building components it's often desirable to receive the raw promises
- * - adds complexity and slows down expression evaluation
- * - makes expression code pre-generation unattractive due to the amount of code that needs to be
- * generated
- * - makes IDE auto-completion and tool support hard
- *
- * **Warning Logs**
- *
- * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
- * promise (to reduce the noise, each expression is logged only once). To disable this logging use
- * `$parseProvider.logPromiseWarnings(false)` api.
- *
- *
- * @param {boolean=} value New value.
- * @returns {boolean|self} Returns the current setting when used as getter and self if used as
- * setter.
- */
- this.unwrapPromises = function(value) {
- if (isDefined(value)) {
- $parseOptions.unwrapPromises = !!value;
- return this;
- } else {
- return $parseOptions.unwrapPromises;
- }
- };
-
-
- /**
- * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
- *
- * @ngdoc method
- * @name ng.$parseProvider#logPromiseWarnings
- * @methodOf ng.$parseProvider
- * @description
- *
- * Controls whether Angular should log a warning on any encounter of a promise in an expression.
- *
- * The default is set to `true`.
- *
- * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
- *
- * @param {boolean=} value New value.
- * @returns {boolean|self} Returns the current setting when used as getter and self if used as
- * setter.
- */
- this.logPromiseWarnings = function(value) {
- if (isDefined(value)) {
- $parseOptions.logPromiseWarnings = value;
- return this;
- } else {
- return $parseOptions.logPromiseWarnings;
- }
- };
-
-
- this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
- $parseOptions.csp = $sniffer.csp;
-
- promiseWarning = function promiseWarningFn(fullExp) {
- if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
- promiseWarningCache[fullExp] = true;
- $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
- 'Automatic unwrapping of promises in Angular expressions is deprecated.');
- };
-
- return function(exp) {
- var parsedExpression;
-
- switch (typeof exp) {
- case 'string':
-
- if (cache.hasOwnProperty(exp)) {
- return cache[exp];
- }
-
- var lexer = new Lexer($parseOptions);
- var parser = new Parser(lexer, $filter, $parseOptions);
- parsedExpression = parser.parse(exp, false);
-
- if (exp !== 'hasOwnProperty') {
- // Only cache the value if it's not going to mess up the cache object
- // This is more performant that using Object.prototype.hasOwnProperty.call
- cache[exp] = parsedExpression;
- }
-
- return parsedExpression;
-
- case 'function':
- return exp;
-
- default:
- return noop;
- }
- };
- }];
-}
-
-/**
- * @ngdoc service
- * @name ng.$q
- * @requires $rootScope
- *
- * @description
- * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
- *
- * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
- * interface for interacting with an object that represents the result of an action that is
- * performed asynchronously, and may or may not be finished at any given point in time.
- *
- * From the perspective of dealing with error handling, deferred and promise APIs are to
- * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
- *
- *
- * // for the purpose of this example let's assume that variables `$q` and `scope` are
- * // available in the current lexical scope (they could have been injected or passed in).
- *
- * function asyncGreet(name) {
- * var deferred = $q.defer();
- *
- * setTimeout(function() {
- * // since this fn executes async in a future turn of the event loop, we need to wrap
- * // our code into an $apply call so that the model changes are properly observed.
- * scope.$apply(function() {
- * deferred.notify('About to greet ' + name + '.');
- *
- * if (okToGreet(name)) {
- * deferred.resolve('Hello, ' + name + '!');
- * } else {
- * deferred.reject('Greeting ' + name + ' is not allowed.');
- * }
- * });
- * }, 1000);
- *
- * return deferred.promise;
- * }
- *
- * var promise = asyncGreet('Robin Hood');
- * promise.then(function(greeting) {
- * alert('Success: ' + greeting);
- * }, function(reason) {
- * alert('Failed: ' + reason);
- * }, function(update) {
- * alert('Got notification: ' + update);
- * });
- *
- *
- * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
- * comes in the way of guarantees that promise and deferred APIs make, see
- * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
- *
- * Additionally the promise api allows for composition that is very hard to do with the
- * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
- * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
- * section on serial or parallel joining of promises.
- *
- *
- * # The Deferred API
- *
- * A new instance of deferred is constructed by calling `$q.defer()`.
- *
- * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
- * that can be used for signaling the successful or unsuccessful completion, as well as the status
- * of the task.
- *
- * **Methods**
- *
- * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
- * constructed via `$q.reject`, the promise will be rejected instead.
- * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
- * resolving it with a rejection constructed via `$q.reject`.
- * - `notify(value)` - provides updates on the status of the promises execution. This may be called
- * multiple times before the promise is either resolved or rejected.
- *
- * **Properties**
- *
- * - promise – `{Promise}` – promise object associated with this deferred.
- *
- *
- * # The Promise API
- *
- * A new promise instance is created when a deferred instance is created and can be retrieved by
- * calling `deferred.promise`.
- *
- * The purpose of the promise object is to allow for interested parties to get access to the result
- * of the deferred task when it completes.
- *
- * **Methods**
- *
- * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
- * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
- * as soon as the result is available. The callbacks are called with a single argument: the result
- * or rejection reason. Additionally, the notify callback may be called zero or more times to
- * provide a progress indication, before the promise is resolved or rejected.
- *
- * This method *returns a new promise* which is resolved or rejected via the return value of the
- * `successCallback`, `errorCallback`. It also notifies via the return value of the
- * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
- * method.
- *
- * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
- *
- * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
- * but to do so without modifying the final value. This is useful to release resources or do some
- * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
- * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
- * more information.
- *
- * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
- * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
- * make your code IE8 compatible.
- *
- * # Chaining promises
- *
- * Because calling the `then` method of a promise returns a new derived promise, it is easily
- * possible to create a chain of promises:
- *
- *
- * promiseB = promiseA.then(function(result) {
- * return result + 1;
- * });
- *
- * // promiseB will be resolved immediately after promiseA is resolved and its value
- * // will be the result of promiseA incremented by 1
- *
- *
- * It is possible to create chains of any length and since a promise can be resolved with another
- * promise (which will defer its resolution further), it is possible to pause/defer resolution of
- * the promises at any point in the chain. This makes it possible to implement powerful APIs like
- * $http's response interceptors.
- *
- *
- * # Differences between Kris Kowal's Q and $q
- *
- * There are two main differences:
- *
- * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
- * mechanism in angular, which means faster propagation of resolution or rejection into your
- * models and avoiding unnecessary browser repaints, which would result in flickering UI.
- * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
- * all the important functionality needed for common async tasks.
- *
- * # Testing
- *
- *
- * it('should simulate promise', inject(function($q, $rootScope) {
- * var deferred = $q.defer();
- * var promise = deferred.promise;
- * var resolvedValue;
- *
- * promise.then(function(value) { resolvedValue = value; });
- * expect(resolvedValue).toBeUndefined();
- *
- * // Simulate resolving of promise
- * deferred.resolve(123);
- * // Note that the 'then' function does not get called synchronously.
- * // This is because we want the promise API to always be async, whether or not
- * // it got called synchronously or asynchronously.
- * expect(resolvedValue).toBeUndefined();
- *
- * // Propagate promise resolution to 'then' functions using $apply().
- * $rootScope.$apply();
- * expect(resolvedValue).toEqual(123);
- * }));
- *
- */
-function $QProvider() {
-
- this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
- return qFactory(function(callback) {
- $rootScope.$evalAsync(callback);
- }, $exceptionHandler);
- }];
-}
-
-
-/**
- * Constructs a promise manager.
- *
- * @param {function(function)} nextTick Function for executing functions in the next turn.
- * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
- * debugging purposes.
- * @returns {object} Promise manager.
- */
-function qFactory(nextTick, exceptionHandler) {
-
- /**
- * @ngdoc
- * @name ng.$q#defer
- * @methodOf ng.$q
- * @description
- * Creates a `Deferred` object which represents a task which will finish in the future.
- *
- * @returns {Deferred} Returns a new instance of deferred.
- */
- var defer = function() {
- var pending = [],
- value, deferred;
-
- deferred = {
-
- resolve: function(val) {
- if (pending) {
- var callbacks = pending;
- pending = undefined;
- value = ref(val);
-
- if (callbacks.length) {
- nextTick(function() {
- var callback;
- for (var i = 0, ii = callbacks.length; i < ii; i++) {
- callback = callbacks[i];
- value.then(callback[0], callback[1], callback[2]);
- }
- });
- }
- }
- },
-
-
- reject: function(reason) {
- deferred.resolve(reject(reason));
- },
-
-
- notify: function(progress) {
- if (pending) {
- var callbacks = pending;
-
- if (pending.length) {
- nextTick(function() {
- var callback;
- for (var i = 0, ii = callbacks.length; i < ii; i++) {
- callback = callbacks[i];
- callback[2](progress);
- }
- });
- }
- }
- },
-
-
- promise: {
- then: function(callback, errback, progressback) {
- var result = defer();
-
- var wrappedCallback = function(value) {
- try {
- result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
- } catch(e) {
- result.reject(e);
- exceptionHandler(e);
- }
- };
-
- var wrappedErrback = function(reason) {
- try {
- result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
- } catch(e) {
- result.reject(e);
- exceptionHandler(e);
- }
- };
-
- var wrappedProgressback = function(progress) {
- try {
- result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
- } catch(e) {
- exceptionHandler(e);
- }
- };
-
- if (pending) {
- pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
- } else {
- value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
- }
-
- return result.promise;
- },
-
- "catch": function(callback) {
- return this.then(null, callback);
- },
-
- "finally": function(callback) {
-
- function makePromise(value, resolved) {
- var result = defer();
- if (resolved) {
- result.resolve(value);
- } else {
- result.reject(value);
- }
- return result.promise;
- }
-
- function handleCallback(value, isResolved) {
- var callbackOutput = null;
- try {
- callbackOutput = (callback ||defaultCallback)();
- } catch(e) {
- return makePromise(e, false);
- }
- if (callbackOutput && isFunction(callbackOutput.then)) {
- return callbackOutput.then(function() {
- return makePromise(value, isResolved);
- }, function(error) {
- return makePromise(error, false);
- });
- } else {
- return makePromise(value, isResolved);
- }
- }
-
- return this.then(function(value) {
- return handleCallback(value, true);
- }, function(error) {
- return handleCallback(error, false);
- });
- }
- }
- };
-
- return deferred;
- };
-
-
- var ref = function(value) {
- if (value && isFunction(value.then)) return value;
- return {
- then: function(callback) {
- var result = defer();
- nextTick(function() {
- result.resolve(callback(value));
- });
- return result.promise;
- }
- };
- };
-
-
- /**
- * @ngdoc
- * @name ng.$q#reject
- * @methodOf ng.$q
- * @description
- * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
- * used to forward rejection in a chain of promises. If you are dealing with the last promise in
- * a promise chain, you don't need to worry about it.
- *
- * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
- * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
- * a promise error callback and you want to forward the error to the promise derived from the
- * current promise, you have to "rethrow" the error by returning a rejection constructed via
- * `reject`.
- *
- *
- * promiseB = promiseA.then(function(result) {
- * // success: do something and resolve promiseB
- * // with the old or a new result
- * return result;
- * }, function(reason) {
- * // error: handle the error if possible and
- * // resolve promiseB with newPromiseOrValue,
- * // otherwise forward the rejection to promiseB
- * if (canHandle(reason)) {
- * // handle the error and recover
- * return newPromiseOrValue;
- * }
- * return $q.reject(reason);
- * });
- *
- *
- * @param {*} reason Constant, message, exception or an object representing the rejection reason.
- * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
- */
- var reject = function(reason) {
- return {
- then: function(callback, errback) {
- var result = defer();
- nextTick(function() {
- try {
- result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
- } catch(e) {
- result.reject(e);
- exceptionHandler(e);
- }
- });
- return result.promise;
- }
- };
- };
-
-
- /**
- * @ngdoc
- * @name ng.$q#when
- * @methodOf ng.$q
- * @description
- * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
- * This is useful when you are dealing with an object that might or might not be a promise, or if
- * the promise comes from a source that can't be trusted.
- *
- * @param {*} value Value or a promise
- * @returns {Promise} Returns a promise of the passed value or promise
- */
- var when = function(value, callback, errback, progressback) {
- var result = defer(),
- done;
-
- var wrappedCallback = function(value) {
- try {
- return (isFunction(callback) ? callback : defaultCallback)(value);
- } catch (e) {
- exceptionHandler(e);
- return reject(e);
- }
- };
-
- var wrappedErrback = function(reason) {
- try {
- return (isFunction(errback) ? errback : defaultErrback)(reason);
- } catch (e) {
- exceptionHandler(e);
- return reject(e);
- }
- };
-
- var wrappedProgressback = function(progress) {
- try {
- return (isFunction(progressback) ? progressback : defaultCallback)(progress);
- } catch (e) {
- exceptionHandler(e);
- }
- };
-
- nextTick(function() {
- ref(value).then(function(value) {
- if (done) return;
- done = true;
- result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
- }, function(reason) {
- if (done) return;
- done = true;
- result.resolve(wrappedErrback(reason));
- }, function(progress) {
- if (done) return;
- result.notify(wrappedProgressback(progress));
- });
- });
-
- return result.promise;
- };
-
-
- function defaultCallback(value) {
- return value;
- }
-
-
- function defaultErrback(reason) {
- return reject(reason);
- }
-
-
- /**
- * @ngdoc
- * @name ng.$q#all
- * @methodOf ng.$q
- * @description
- * Combines multiple promises into a single promise that is resolved when all of the input
- * promises are resolved.
- *
- * @param {Array.|Object.} promises An array or hash of promises.
- * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
- * each value corresponding to the promise at the same index/key in the `promises` array/hash.
- * If any of the promises is resolved with a rejection, this resulting promise will be rejected
- * with the same rejection value.
- */
- function all(promises) {
- var deferred = defer(),
- counter = 0,
- results = isArray(promises) ? [] : {};
-
- forEach(promises, function(promise, key) {
- counter++;
- ref(promise).then(function(value) {
- if (results.hasOwnProperty(key)) return;
- results[key] = value;
- if (!(--counter)) deferred.resolve(results);
- }, function(reason) {
- if (results.hasOwnProperty(key)) return;
- deferred.reject(reason);
- });
- });
-
- if (counter === 0) {
- deferred.resolve(results);
- }
-
- return deferred.promise;
- }
-
- return {
- defer: defer,
- reject: reject,
- when: when,
- all: all
- };
-}
-
-/**
- * DESIGN NOTES
- *
- * The design decisions behind the scope are heavily favored for speed and memory consumption.
- *
- * The typical use of scope is to watch the expressions, which most of the time return the same
- * value as last time so we optimize the operation.
- *
- * Closures construction is expensive in terms of speed as well as memory:
- * - No closures, instead use prototypical inheritance for API
- * - Internal state needs to be stored on scope directly, which means that private state is
- * exposed as $$____ properties
- *
- * Loop operations are optimized by using while(count--) { ... }
- * - this means that in order to keep the same order of execution as addition we have to add
- * items to the array at the beginning (shift) instead of at the end (push)
- *
- * Child scopes are created and removed often
- * - Using an array would be slow since inserts in middle are expensive so we use linked list
- *
- * There are few watches then a lot of observers. This is why you don't want the observer to be
- * implemented in the same way as watch. Watch requires return of initialization function which
- * are expensive to construct.
- */
-
-
-/**
- * @ngdoc object
- * @name ng.$rootScopeProvider
- * @description
- *
- * Provider for the $rootScope service.
- */
-
-/**
- * @ngdoc function
- * @name ng.$rootScopeProvider#digestTtl
- * @methodOf ng.$rootScopeProvider
- * @description
- *
- * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
- * assuming that the model is unstable.
- *
- * The current default is 10 iterations.
- *
- * In complex applications it's possible that the dependencies between `$watch`s will result in
- * several digest iterations. However if an application needs more than the default 10 digest
- * iterations for its model to stabilize then you should investigate what is causing the model to
- * continuously change during the digest.
- *
- * Increasing the TTL could have performance implications, so you should not change it without
- * proper justification.
- *
- * @param {number} limit The number of digest iterations.
- */
-
-
-/**
- * @ngdoc object
- * @name ng.$rootScope
- * @description
- *
- * Every application has a single root {@link ng.$rootScope.Scope scope}.
- * All other scopes are descendant scopes of the root scope. Scopes provide separation
- * between the model and the view, via a mechanism for watching the model for changes.
- * They also provide an event emission/broadcast and subscription facility. See the
- * {@link guide/scope developer guide on scopes}.
- */
-function $RootScopeProvider(){
- var TTL = 10;
- var $rootScopeMinErr = minErr('$rootScope');
- var lastDirtyWatch = null;
-
- this.digestTtl = function(value) {
- if (arguments.length) {
- TTL = value;
- }
- return TTL;
- };
-
- this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
- function( $injector, $exceptionHandler, $parse, $browser) {
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope
- *
- * @description
- * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
- * {@link AUTO.$injector $injector}. Child scopes are created using the
- * {@link ng.$rootScope.Scope#methods_$new $new()} method. (Most scopes are created automatically when
- * compiled HTML template is executed.)
- *
- * Here is a simple scope snippet to show how you can interact with the scope.
- *
- *
- *
- *
- * # Inheritance
- * A scope can inherit from a parent scope, as in this example:
- *
- *
- *
- * @param {Object.=} providers Map of service factory which need to be
- * provided for the current scope. Defaults to {@link ng}.
- * @param {Object.=} instanceCache Provides pre-instantiated services which should
- * append/override services provided by `providers`. This is handy
- * when unit-testing and having the need to override a default
- * service.
- * @returns {Object} Newly created scope.
- *
- */
- function Scope() {
- this.$id = nextUid();
- this.$$phase = this.$parent = this.$$watchers =
- this.$$nextSibling = this.$$prevSibling =
- this.$$childHead = this.$$childTail = null;
- this['this'] = this.$root = this;
- this.$$destroyed = false;
- this.$$asyncQueue = [];
- this.$$postDigestQueue = [];
- this.$$listeners = {};
- this.$$listenerCount = {};
- this.$$isolateBindings = {};
- }
-
- /**
- * @ngdoc property
- * @name ng.$rootScope.Scope#$id
- * @propertyOf ng.$rootScope.Scope
- * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
- * debugging.
- */
-
-
- Scope.prototype = {
- constructor: Scope,
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$new
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Creates a new child {@link ng.$rootScope.Scope scope}.
- *
- * The parent scope will propagate the {@link ng.$rootScope.Scope#methods_$digest $digest()} and
- * {@link ng.$rootScope.Scope#methods_$digest $digest()} events. The scope can be removed from the
- * scope hierarchy using {@link ng.$rootScope.Scope#methods_$destroy $destroy()}.
- *
- * {@link ng.$rootScope.Scope#methods_$destroy $destroy()} must be called on a scope when it is
- * desired for the scope and its child scopes to be permanently detached from the parent and
- * thus stop participating in model change detection and listener notification by invoking.
- *
- * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
- * parent scope. The scope is isolated, as it can not see parent scope properties.
- * When creating widgets, it is useful for the widget to not accidentally read parent
- * state.
- *
- * @returns {Object} The newly created child scope.
- *
- */
- $new: function(isolate) {
- var ChildScope,
- child;
-
- if (isolate) {
- child = new Scope();
- child.$root = this.$root;
- // ensure that there is just one async queue per $rootScope and its children
- child.$$asyncQueue = this.$$asyncQueue;
- child.$$postDigestQueue = this.$$postDigestQueue;
- } else {
- ChildScope = function() {}; // should be anonymous; This is so that when the minifier munges
- // the name it does not become random set of chars. This will then show up as class
- // name in the web inspector.
- ChildScope.prototype = this;
- child = new ChildScope();
- child.$id = nextUid();
- }
- child['this'] = child;
- child.$$listeners = {};
- child.$$listenerCount = {};
- child.$parent = this;
- child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
- child.$$prevSibling = this.$$childTail;
- if (this.$$childHead) {
- this.$$childTail.$$nextSibling = child;
- this.$$childTail = child;
- } else {
- this.$$childHead = this.$$childTail = child;
- }
- return child;
- },
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$watch
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
- *
- * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#methods_$digest
- * $digest()} and should return the value that will be watched. (Since
- * {@link ng.$rootScope.Scope#methods_$digest $digest()} reruns when it detects changes the
- * `watchExpression` can execute multiple times per
- * {@link ng.$rootScope.Scope#methods_$digest $digest()} and should be idempotent.)
- * - The `listener` is called only when the value from the current `watchExpression` and the
- * previous call to `watchExpression` are not equal (with the exception of the initial run,
- * see below). The inequality is determined according to
- * {@link angular.equals} function. To save the value of the object for later comparison,
- * the {@link angular.copy} function is used. It also means that watching complex options
- * will have adverse memory and performance implications.
- * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
- * This is achieved by rerunning the watchers until no changes are detected. The rerun
- * iteration limit is 10 to prevent an infinite loop deadlock.
- *
- *
- * If you want to be notified whenever {@link ng.$rootScope.Scope#methods_$digest $digest} is called,
- * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
- * can execute multiple times per {@link ng.$rootScope.Scope#methods_$digest $digest} cycle when a
- * change is detected, be prepared for multiple calls to your listener.)
- *
- * After a watcher is registered with the scope, the `listener` fn is called asynchronously
- * (via {@link ng.$rootScope.Scope#methods_$evalAsync $evalAsync}) to initialize the
- * watcher. In rare cases, this is undesirable because the listener is called when the result
- * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
- * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
- * listener was called due to initialization.
- *
- * The example below contains an illustration of using a function as your $watch listener
- *
- *
- * # Example
- *
- // let's assume that scope was dependency injected as the $rootScope
- var scope = $rootScope;
- scope.name = 'misko';
- scope.counter = 0;
-
- expect(scope.counter).toEqual(0);
- scope.$watch('name', function(newValue, oldValue) {
- scope.counter = scope.counter + 1;
- });
- expect(scope.counter).toEqual(0);
-
- scope.$digest();
- // no variable change
- expect(scope.counter).toEqual(0);
-
- scope.name = 'adam';
- scope.$digest();
- expect(scope.counter).toEqual(1);
-
-
-
- // Using a listener function
- var food;
- scope.foodCounter = 0;
- expect(scope.foodCounter).toEqual(0);
- scope.$watch(
- // This is the listener function
- function() { return food; },
- // This is the change handler
- function(newValue, oldValue) {
- if ( newValue !== oldValue ) {
- // Only increment the counter if the value changed
- scope.foodCounter = scope.foodCounter + 1;
- }
- }
- );
- // No digest has been run so the counter will be zero
- expect(scope.foodCounter).toEqual(0);
-
- // Run the digest but since food has not changed count will still be zero
- scope.$digest();
- expect(scope.foodCounter).toEqual(0);
-
- // Update food and run digest. Now the counter will increment
- food = 'cheeseburger';
- scope.$digest();
- expect(scope.foodCounter).toEqual(1);
-
- *
- *
- *
- *
- * @param {(function()|string)} watchExpression Expression that is evaluated on each
- * {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. A change in the return value triggers
- * a call to the `listener`.
- *
- * - `string`: Evaluated as {@link guide/expression expression}
- * - `function(scope)`: called with current `scope` as a parameter.
- * @param {(function()|string)=} listener Callback called whenever the return value of
- * the `watchExpression` changes.
- *
- * - `string`: Evaluated as {@link guide/expression expression}
- * - `function(newValue, oldValue, scope)`: called with current and previous values as
- * parameters.
- *
- * @param {boolean=} objectEquality Compare object for equality rather than for reference.
- * @returns {function()} Returns a deregistration function for this listener.
- */
- $watch: function(watchExp, listener, objectEquality) {
- var scope = this,
- get = compileToFn(watchExp, 'watch'),
- array = scope.$$watchers,
- watcher = {
- fn: listener,
- last: initWatchVal,
- get: get,
- exp: watchExp,
- eq: !!objectEquality
- };
-
- lastDirtyWatch = null;
-
- // in the case user pass string, we need to compile it, do we really need this ?
- if (!isFunction(listener)) {
- var listenFn = compileToFn(listener || noop, 'listener');
- watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
- }
-
- if (typeof watchExp == 'string' && get.constant) {
- var originalFn = watcher.fn;
- watcher.fn = function(newVal, oldVal, scope) {
- originalFn.call(this, newVal, oldVal, scope);
- arrayRemove(array, watcher);
- };
- }
-
- if (!array) {
- array = scope.$$watchers = [];
- }
- // we use unshift since we use a while loop in $digest for speed.
- // the while loop reads in reverse order.
- array.unshift(watcher);
-
- return function() {
- arrayRemove(array, watcher);
- lastDirtyWatch = null;
- };
- },
-
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$watchCollection
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Shallow watches the properties of an object and fires whenever any of the properties change
- * (for arrays, this implies watching the array items; for object maps, this implies watching
- * the properties). If a change is detected, the `listener` callback is fired.
- *
- * - The `obj` collection is observed via standard $watch operation and is examined on every
- * call to $digest() to see if any items have been added, removed, or moved.
- * - The `listener` is called whenever anything within the `obj` has changed. Examples include
- * adding, removing, and moving items belonging to an object or array.
- *
- *
- * # Example
- *
- *
- *
- * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The
- * expression value should evaluate to an object or an array which is observed on each
- * {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. Any shallow change within the
- * collection will trigger a call to the `listener`.
- *
- * @param {function(newCollection, oldCollection, scope)} listener a callback function that is
- * fired with both the `newCollection` and `oldCollection` as parameters.
- * The `newCollection` object is the newly modified data obtained from the `obj` expression
- * and the `oldCollection` object is a copy of the former collection data.
- * The `scope` refers to the current scope.
- *
- * @returns {function()} Returns a de-registration function for this listener. When the
- * de-registration function is executed, the internal watch operation is terminated.
- */
- $watchCollection: function(obj, listener) {
- var self = this;
- var oldValue;
- var newValue;
- var changeDetected = 0;
- var objGetter = $parse(obj);
- var internalArray = [];
- var internalObject = {};
- var oldLength = 0;
-
- function $watchCollectionWatch() {
- newValue = objGetter(self);
- var newLength, key;
-
- if (!isObject(newValue)) {
- if (oldValue !== newValue) {
- oldValue = newValue;
- changeDetected++;
- }
- } else if (isArrayLike(newValue)) {
- if (oldValue !== internalArray) {
- // we are transitioning from something which was not an array into array.
- oldValue = internalArray;
- oldLength = oldValue.length = 0;
- changeDetected++;
- }
-
- newLength = newValue.length;
-
- if (oldLength !== newLength) {
- // if lengths do not match we need to trigger change notification
- changeDetected++;
- oldValue.length = oldLength = newLength;
- }
- // copy the items to oldValue and look for changes.
- for (var i = 0; i < newLength; i++) {
- if (oldValue[i] !== newValue[i]) {
- changeDetected++;
- oldValue[i] = newValue[i];
- }
- }
- } else {
- if (oldValue !== internalObject) {
- // we are transitioning from something which was not an object into object.
- oldValue = internalObject = {};
- oldLength = 0;
- changeDetected++;
- }
- // copy the items to oldValue and look for changes.
- newLength = 0;
- for (key in newValue) {
- if (newValue.hasOwnProperty(key)) {
- newLength++;
- if (oldValue.hasOwnProperty(key)) {
- if (oldValue[key] !== newValue[key]) {
- changeDetected++;
- oldValue[key] = newValue[key];
- }
- } else {
- oldLength++;
- oldValue[key] = newValue[key];
- changeDetected++;
- }
- }
- }
- if (oldLength > newLength) {
- // we used to have more keys, need to find them and destroy them.
- changeDetected++;
- for(key in oldValue) {
- if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
- oldLength--;
- delete oldValue[key];
- }
- }
- }
- }
- return changeDetected;
- }
-
- function $watchCollectionAction() {
- listener(newValue, oldValue, self);
- }
-
- return this.$watch($watchCollectionWatch, $watchCollectionAction);
- },
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$digest
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Processes all of the {@link ng.$rootScope.Scope#methods_$watch watchers} of the current scope and
- * its children. Because a {@link ng.$rootScope.Scope#methods_$watch watcher}'s listener can change
- * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#methods_$watch watchers}
- * until no more listeners are firing. This means that it is possible to get into an infinite
- * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
- * iterations exceeds 10.
- *
- * Usually, you don't call `$digest()` directly in
- * {@link ng.directive:ngController controllers} or in
- * {@link ng.$compileProvider#methods_directive directives}.
- * Instead, you should call {@link ng.$rootScope.Scope#methods_$apply $apply()} (typically from within
- * a {@link ng.$compileProvider#methods_directive directives}), which will force a `$digest()`.
- *
- * If you want to be notified whenever `$digest()` is called,
- * you can register a `watchExpression` function with
- * {@link ng.$rootScope.Scope#methods_$watch $watch()} with no `listener`.
- *
- * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
- *
- * # Example
- *
- *
- */
- $digest: function() {
- var watch, value, last,
- watchers,
- asyncQueue = this.$$asyncQueue,
- postDigestQueue = this.$$postDigestQueue,
- length,
- dirty, ttl = TTL,
- next, current, target = this,
- watchLog = [],
- logIdx, logMsg, asyncTask;
-
- beginPhase('$digest');
-
- lastDirtyWatch = null;
-
- do { // "while dirty" loop
- dirty = false;
- current = target;
-
- while(asyncQueue.length) {
- try {
- asyncTask = asyncQueue.shift();
- asyncTask.scope.$eval(asyncTask.expression);
- } catch (e) {
- clearPhase();
- $exceptionHandler(e);
- }
- lastDirtyWatch = null;
- }
-
- traverseScopesLoop:
- do { // "traverse the scopes" loop
- if ((watchers = current.$$watchers)) {
- // process our watches
- length = watchers.length;
- while (length--) {
- try {
- watch = watchers[length];
- // Most common watches are on primitives, in which case we can short
- // circuit it with === operator, only when === fails do we use .equals
- if (watch) {
- if ((value = watch.get(current)) !== (last = watch.last) &&
- !(watch.eq
- ? equals(value, last)
- : (typeof value == 'number' && typeof last == 'number'
- && isNaN(value) && isNaN(last)))) {
- dirty = true;
- lastDirtyWatch = watch;
- watch.last = watch.eq ? copy(value) : value;
- watch.fn(value, ((last === initWatchVal) ? value : last), current);
- if (ttl < 5) {
- logIdx = 4 - ttl;
- if (!watchLog[logIdx]) watchLog[logIdx] = [];
- logMsg = (isFunction(watch.exp))
- ? 'fn: ' + (watch.exp.name || watch.exp.toString())
- : watch.exp;
- logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
- watchLog[logIdx].push(logMsg);
- }
- } else if (watch === lastDirtyWatch) {
- // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
- // have already been tested.
- dirty = false;
- break traverseScopesLoop;
- }
- }
- } catch (e) {
- clearPhase();
- $exceptionHandler(e);
- }
- }
- }
-
- // Insanity Warning: scope depth-first traversal
- // yes, this code is a bit crazy, but it works and we have tests to prove it!
- // this piece should be kept in sync with the traversal in $broadcast
- if (!(next = (current.$$childHead ||
- (current !== target && current.$$nextSibling)))) {
- while(current !== target && !(next = current.$$nextSibling)) {
- current = current.$parent;
- }
- }
- } while ((current = next));
-
- // `break traverseScopesLoop;` takes us to here
-
- if((dirty || asyncQueue.length) && !(ttl--)) {
- clearPhase();
- throw $rootScopeMinErr('infdig',
- '{0} $digest() iterations reached. Aborting!\n' +
- 'Watchers fired in the last 5 iterations: {1}',
- TTL, toJson(watchLog));
- }
-
- } while (dirty || asyncQueue.length);
-
- clearPhase();
-
- while(postDigestQueue.length) {
- try {
- postDigestQueue.shift()();
- } catch (e) {
- $exceptionHandler(e);
- }
- }
- },
-
-
- /**
- * @ngdoc event
- * @name ng.$rootScope.Scope#$destroy
- * @eventOf ng.$rootScope.Scope
- * @eventType broadcast on scope being destroyed
- *
- * @description
- * Broadcasted when a scope and its children are being destroyed.
- *
- * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
- * clean up DOM bindings before an element is removed from the DOM.
- */
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$destroy
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Removes the current scope (and all of its children) from the parent scope. Removal implies
- * that calls to {@link ng.$rootScope.Scope#methods_$digest $digest()} will no longer
- * propagate to the current scope and its children. Removal also implies that the current
- * scope is eligible for garbage collection.
- *
- * The `$destroy()` is usually used by directives such as
- * {@link ng.directive:ngRepeat ngRepeat} for managing the
- * unrolling of the loop.
- *
- * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
- * Application code can register a `$destroy` event handler that will give it a chance to
- * perform any necessary cleanup.
- *
- * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
- * clean up DOM bindings before an element is removed from the DOM.
- */
- $destroy: function() {
- // we can't destroy the root scope or a scope that has been already destroyed
- if (this.$$destroyed) return;
- var parent = this.$parent;
-
- this.$broadcast('$destroy');
- this.$$destroyed = true;
- if (this === $rootScope) return;
-
- forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
-
- if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
- if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
- if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
- if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
-
- // This is bogus code that works around Chrome's GC leak
- // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
- this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
- this.$$childTail = null;
- },
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$eval
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Executes the `expression` on the current scope and returns the result. Any exceptions in
- * the expression are propagated (uncaught). This is useful when evaluating Angular
- * expressions.
- *
- * # Example
- *
- *
- * @param {(string|function())=} expression An angular expression to be executed.
- *
- * - `string`: execute using the rules as defined in {@link guide/expression expression}.
- * - `function(scope)`: execute the function with the current `scope` parameter.
- *
- * @param {(object)=} locals Local variables object, useful for overriding values in scope.
- * @returns {*} The result of evaluating the expression.
- */
- $eval: function(expr, locals) {
- return $parse(expr)(this, locals);
- },
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$evalAsync
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Executes the expression on the current scope at a later point in time.
- *
- * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
- * that:
- *
- * - it will execute after the function that scheduled the evaluation (preferably before DOM
- * rendering).
- * - at least one {@link ng.$rootScope.Scope#methods_$digest $digest cycle} will be performed after
- * `expression` execution.
- *
- * Any exceptions from the execution of the expression are forwarded to the
- * {@link ng.$exceptionHandler $exceptionHandler} service.
- *
- * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
- * will be scheduled. However, it is encouraged to always call code that changes the model
- * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
- *
- * @param {(string|function())=} expression An angular expression to be executed.
- *
- * - `string`: execute using the rules as defined in {@link guide/expression expression}.
- * - `function(scope)`: execute the function with the current `scope` parameter.
- *
- */
- $evalAsync: function(expr) {
- // if we are outside of an $digest loop and this is the first time we are scheduling async
- // task also schedule async auto-flush
- if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
- $browser.defer(function() {
- if ($rootScope.$$asyncQueue.length) {
- $rootScope.$digest();
- }
- });
- }
-
- this.$$asyncQueue.push({scope: this, expression: expr});
- },
-
- $$postDigest : function(fn) {
- this.$$postDigestQueue.push(fn);
- },
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$apply
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * `$apply()` is used to execute an expression in angular from outside of the angular
- * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
- * Because we are calling into the angular framework we need to perform proper scope life
- * cycle of {@link ng.$exceptionHandler exception handling},
- * {@link ng.$rootScope.Scope#methods_$digest executing watches}.
- *
- * ## Life cycle
- *
- * # Pseudo-Code of `$apply()`
- *
- *
- *
- * Scope's `$apply()` method transitions through the following stages:
- *
- * 1. The {@link guide/expression expression} is executed using the
- * {@link ng.$rootScope.Scope#methods_$eval $eval()} method.
- * 2. Any exceptions from the execution of the expression are forwarded to the
- * {@link ng.$exceptionHandler $exceptionHandler} service.
- * 3. The {@link ng.$rootScope.Scope#methods_$watch watch} listeners are fired immediately after the
- * expression was executed using the {@link ng.$rootScope.Scope#methods_$digest $digest()} method.
- *
- *
- * @param {(string|function())=} exp An angular expression to be executed.
- *
- * - `string`: execute using the rules as defined in {@link guide/expression expression}.
- * - `function(scope)`: execute the function with current `scope` parameter.
- *
- * @returns {*} The result of evaluating the expression.
- */
- $apply: function(expr) {
- try {
- beginPhase('$apply');
- return this.$eval(expr);
- } catch (e) {
- $exceptionHandler(e);
- } finally {
- clearPhase();
- try {
- $rootScope.$digest();
- } catch (e) {
- $exceptionHandler(e);
- throw e;
- }
- }
- },
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$on
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Listens on events of a given type. See {@link ng.$rootScope.Scope#methods_$emit $emit} for
- * discussion of event life cycle.
- *
- * The event listener function format is: `function(event, args...)`. The `event` object
- * passed into the listener has the following attributes:
- *
- * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
- * `$broadcast`-ed.
- * - `currentScope` - `{Scope}`: the current scope which is handling the event.
- * - `name` - `{string}`: name of the event.
- * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
- * further event propagation (available only for events that were `$emit`-ed).
- * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
- * to true.
- * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
- *
- * @param {string} name Event name to listen on.
- * @param {function(event, args...)} listener Function to call when the event is emitted.
- * @returns {function()} Returns a deregistration function for this listener.
- */
- $on: function(name, listener) {
- var namedListeners = this.$$listeners[name];
- if (!namedListeners) {
- this.$$listeners[name] = namedListeners = [];
- }
- namedListeners.push(listener);
-
- var current = this;
- do {
- if (!current.$$listenerCount[name]) {
- current.$$listenerCount[name] = 0;
- }
- current.$$listenerCount[name]++;
- } while ((current = current.$parent));
-
- var self = this;
- return function() {
- namedListeners[indexOf(namedListeners, listener)] = null;
- decrementListenerCount(self, 1, name);
- };
- },
-
-
- /**
- * @ngdoc function
- * @name ng.$rootScope.Scope#$emit
- * @methodOf ng.$rootScope.Scope
- * @function
- *
- * @description
- * Dispatches an event `name` upwards through the scope hierarchy notifying the
- * registered {@link ng.$rootScope.Scope#methods_$on} listeners.
- *
- * The event life cycle starts at the scope on which `$emit` was called. All
- * {@link ng.$rootScope.Scope#methods_$on listeners} listening for `name` event on this scope get
- * notified. Afterwards, the event traverses upwards toward the root scope and calls all
- * registered listeners along the way. The event will stop propagating if one of the listeners
- * cancels it.
- *
- * Any exception emitted from the {@link ng.$rootScope.Scope#methods_$on listeners} will be passed
- * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
- *
- * @param {string} name Event name to emit.
- * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
- * @return {Object} Event object (see {@link ng.$rootScope.Scope#methods_$on}).
- */
- $emit: function(name, args) {
- var empty = [],
- namedListeners,
- scope = this,
- stopPropagation = false,
- event = {
- name: name,
- targetScope: scope,
- stopPropagation: function() {stopPropagation = true;},
- preventDefault: function() {
- event.defaultPrevented = true;
- },
- defaultPrevented: false
- },
- listenerArgs = concat([event], arguments, 1),
- i, length;
-
- do {
- namedListeners = scope.$$listeners[name] || empty;
- event.currentScope = scope;
- for (i=0, length=namedListeners.length; i= 8 ) {
- normalizedVal = urlResolve(uri).href;
- if (normalizedVal !== '' && !normalizedVal.match(regex)) {
- return 'unsafe:'+normalizedVal;
- }
- }
- return uri;
- };
- };
-}
-
-var $sceMinErr = minErr('$sce');
-
-var SCE_CONTEXTS = {
- HTML: 'html',
- CSS: 'css',
- URL: 'url',
- // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
- // url. (e.g. ng-include, script src, templateUrl)
- RESOURCE_URL: 'resourceUrl',
- JS: 'js'
-};
-
-// Helper functions follow.
-
-// Copied from:
-// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
-// Prereq: s is a string.
-function escapeForRegexp(s) {
- return s.replace(/([-()\[\]{}+?*.$\^|,:# -1) {
- throw $sceMinErr('iwcard',
- 'Illegal sequence *** in string matcher. String: {0}', matcher);
- }
- matcher = escapeForRegexp(matcher).
- replace('\\*\\*', '.*').
- replace('\\*', '[^:/.?&;]*');
- return new RegExp('^' + matcher + '$');
- } else if (isRegExp(matcher)) {
- // The only other type of matcher allowed is a Regexp.
- // Match entire URL / disallow partial matches.
- // Flags are reset (i.e. no global, ignoreCase or multiline)
- return new RegExp('^' + matcher.source + '$');
- } else {
- throw $sceMinErr('imatcher',
- 'Matchers may only be "self", string patterns or RegExp objects');
- }
-}
-
-
-function adjustMatchers(matchers) {
- var adjustedMatchers = [];
- if (isDefined(matchers)) {
- forEach(matchers, function(matcher) {
- adjustedMatchers.push(adjustMatcher(matcher));
- });
- }
- return adjustedMatchers;
-}
-
-
-/**
- * @ngdoc service
- * @name ng.$sceDelegate
- * @function
- *
- * @description
- *
- * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
- * Contextual Escaping (SCE)} services to AngularJS.
- *
- * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
- * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
- * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
- * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
- * work because `$sce` delegates to `$sceDelegate` for these operations.
- *
- * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
- *
- * The default instance of `$sceDelegate` should work out of the box with little pain. While you
- * can override it completely to change the behavior of `$sce`, the common case would
- * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
- * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
- * templates. Refer {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist
- * $sceDelegateProvider.resourceUrlWhitelist} and {@link
- * ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
- */
-
-/**
- * @ngdoc object
- * @name ng.$sceDelegateProvider
- * @description
- *
- * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
- * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
- * that the URLs used for sourcing Angular templates are safe. Refer {@link
- * ng.$sceDelegateProvider#methods_resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
- * {@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
- *
- * For the general details about this service in Angular, read the main page for {@link ng.$sce
- * Strict Contextual Escaping (SCE)}.
- *
- * **Example**: Consider the following case.
- *
- * - your app is hosted at url `http://myapp.example.com/`
- * - but some of your templates are hosted on other domains you control such as
- * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
- * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
- *
- * Here is what a secure configuration for this scenario might look like:
- *
- *
- * angular.module('myApp', []).config(function($sceDelegateProvider) {
- * $sceDelegateProvider.resourceUrlWhitelist([
- * // Allow same origin resource loads.
- * 'self',
- * // Allow loading from our assets domain. Notice the difference between * and **.
- * 'http://srv*.assets.example.com/**']);
- *
- * // The blacklist overrides the whitelist so the open redirect here is blocked.
- * $sceDelegateProvider.resourceUrlBlacklist([
- * 'http://myapp.example.com/clickThru**']);
- * });
- *
- */
-
-function $SceDelegateProvider() {
- this.SCE_CONTEXTS = SCE_CONTEXTS;
-
- // Resource URLs can also be trusted by policy.
- var resourceUrlWhitelist = ['self'],
- resourceUrlBlacklist = [];
-
- /**
- * @ngdoc function
- * @name ng.sceDelegateProvider#resourceUrlWhitelist
- * @methodOf ng.$sceDelegateProvider
- * @function
- *
- * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
- * provided. This must be an array or null. A snapshot of this array is used so further
- * changes to the array are ignored.
- *
- * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
- * allowed in this array.
- *
- * Note: **an empty whitelist array will block all URLs**!
- *
- * @return {Array} the currently set whitelist array.
- *
- * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
- * same origin resource requests.
- *
- * @description
- * Sets/Gets the whitelist of trusted resource URLs.
- */
- this.resourceUrlWhitelist = function (value) {
- if (arguments.length) {
- resourceUrlWhitelist = adjustMatchers(value);
- }
- return resourceUrlWhitelist;
- };
-
- /**
- * @ngdoc function
- * @name ng.sceDelegateProvider#resourceUrlBlacklist
- * @methodOf ng.$sceDelegateProvider
- * @function
- *
- * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
- * provided. This must be an array or null. A snapshot of this array is used so further
- * changes to the array are ignored.
- *
- * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
- * allowed in this array.
- *
- * The typical usage for the blacklist is to **block
- * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
- * these would otherwise be trusted but actually return content from the redirected domain.
- *
- * Finally, **the blacklist overrides the whitelist** and has the final say.
- *
- * @return {Array} the currently set blacklist array.
- *
- * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
- * is no blacklist.)
- *
- * @description
- * Sets/Gets the blacklist of trusted resource URLs.
- */
-
- this.resourceUrlBlacklist = function (value) {
- if (arguments.length) {
- resourceUrlBlacklist = adjustMatchers(value);
- }
- return resourceUrlBlacklist;
- };
-
- this.$get = ['$injector', function($injector) {
-
- var htmlSanitizer = function htmlSanitizer(html) {
- throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
- };
-
- if ($injector.has('$sanitize')) {
- htmlSanitizer = $injector.get('$sanitize');
- }
-
-
- function matchUrl(matcher, parsedUrl) {
- if (matcher === 'self') {
- return urlIsSameOrigin(parsedUrl);
- } else {
- // definitely a regex. See adjustMatchers()
- return !!matcher.exec(parsedUrl.href);
- }
- }
-
- function isResourceUrlAllowedByPolicy(url) {
- var parsedUrl = urlResolve(url.toString());
- var i, n, allowed = false;
- // Ensure that at least one item from the whitelist allows this url.
- for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
- if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
- allowed = true;
- break;
- }
- }
- if (allowed) {
- // Ensure that no item from the blacklist blocked this url.
- for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
- if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
- allowed = false;
- break;
- }
- }
- }
- return allowed;
- }
-
- function generateHolderType(Base) {
- var holderType = function TrustedValueHolderType(trustedValue) {
- this.$$unwrapTrustedValue = function() {
- return trustedValue;
- };
- };
- if (Base) {
- holderType.prototype = new Base();
- }
- holderType.prototype.valueOf = function sceValueOf() {
- return this.$$unwrapTrustedValue();
- };
- holderType.prototype.toString = function sceToString() {
- return this.$$unwrapTrustedValue().toString();
- };
- return holderType;
- }
-
- var trustedValueHolderBase = generateHolderType(),
- byType = {};
-
- byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
- byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
- byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
- byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
- byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
-
- /**
- * @ngdoc method
- * @name ng.$sceDelegate#trustAs
- * @methodOf ng.$sceDelegate
- *
- * @description
- * Returns an object that is trusted by angular for use in specified strict
- * contextual escaping contexts (such as ng-html-bind-unsafe, ng-include, any src
- * attribute interpolation, any dom event binding attribute interpolation
- * such as for onclick, etc.) that uses the provided value.
- * See {@link ng.$sce $sce} for enabling strict contextual escaping.
- *
- * @param {string} type The kind of context in which this value is safe for use. e.g. url,
- * resourceUrl, html, js and css.
- * @param {*} value The value that that should be considered trusted/safe.
- * @returns {*} A value that can be used to stand in for the provided `value` in places
- * where Angular expects a $sce.trustAs() return value.
- */
- function trustAs(type, trustedValue) {
- var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
- if (!Constructor) {
- throw $sceMinErr('icontext',
- 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
- type, trustedValue);
- }
- if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
- return trustedValue;
- }
- // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
- // mutable objects, we ensure here that the value passed in is actually a string.
- if (typeof trustedValue !== 'string') {
- throw $sceMinErr('itype',
- 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
- type);
- }
- return new Constructor(trustedValue);
- }
-
- /**
- * @ngdoc method
- * @name ng.$sceDelegate#valueOf
- * @methodOf ng.$sceDelegate
- *
- * @description
- * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#methods_trustAs
- * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
- * ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}.
- *
- * If the passed parameter is not a value that had been returned by {@link
- * ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}, returns it as-is.
- *
- * @param {*} value The result of a prior {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}
- * call or anything else.
- * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#methods_trustAs
- * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
- * `value` unchanged.
- */
- function valueOf(maybeTrusted) {
- if (maybeTrusted instanceof trustedValueHolderBase) {
- return maybeTrusted.$$unwrapTrustedValue();
- } else {
- return maybeTrusted;
- }
- }
-
- /**
- * @ngdoc method
- * @name ng.$sceDelegate#getTrusted
- * @methodOf ng.$sceDelegate
- *
- * @description
- * Takes the result of a {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`} call and
- * returns the originally supplied value if the queried context type is a supertype of the
- * created type. If this condition isn't satisfied, throws an exception.
- *
- * @param {string} type The kind of context in which this value is to be used.
- * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#methods_trustAs
- * `$sceDelegate.trustAs`} call.
- * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#methods_trustAs
- * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
- */
- function getTrusted(type, maybeTrusted) {
- if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
- return maybeTrusted;
- }
- var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
- if (constructor && maybeTrusted instanceof constructor) {
- return maybeTrusted.$$unwrapTrustedValue();
- }
- // If we get here, then we may only take one of two actions.
- // 1. sanitize the value for the requested type, or
- // 2. throw an exception.
- if (type === SCE_CONTEXTS.RESOURCE_URL) {
- if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
- return maybeTrusted;
- } else {
- throw $sceMinErr('insecurl',
- 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
- maybeTrusted.toString());
- }
- } else if (type === SCE_CONTEXTS.HTML) {
- return htmlSanitizer(maybeTrusted);
- }
- throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
- }
-
- return { trustAs: trustAs,
- getTrusted: getTrusted,
- valueOf: valueOf };
- }];
-}
-
-
-/**
- * @ngdoc object
- * @name ng.$sceProvider
- * @description
- *
- * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
- * - enable/disable Strict Contextual Escaping (SCE) in a module
- * - override the default implementation with a custom delegate
- *
- * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
- */
-
-/* jshint maxlen: false*/
-
-/**
- * @ngdoc service
- * @name ng.$sce
- * @function
- *
- * @description
- *
- * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
- *
- * # Strict Contextual Escaping
- *
- * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
- * contexts to result in a value that is marked as safe to use for that context. One example of
- * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
- * to these contexts as privileged or SCE contexts.
- *
- * As of version 1.2, Angular ships with SCE enabled by default.
- *
- * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
- * one to execute arbitrary javascript by the use of the expression() syntax. Refer
- * to learn more about them.
- * You can ensure your document is in standards mode and not quirks mode by adding ``
- * to the top of your HTML document.
- *
- * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
- * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
- *
- * Here's an example of a binding in a privileged context:
- *
- *
- *
- *
- *
- *
- * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
- * disabled, this application allows the user to render arbitrary HTML into the DIV.
- * In a more realistic example, one may be rendering user comments, blog articles, etc. via
- * bindings. (HTML is just one example of a context where rendering user controlled input creates
- * security vulnerabilities.)
- *
- * For the case of HTML, you might use a library, either on the client side, or on the server side,
- * to sanitize unsafe HTML before binding to the value and rendering it in the document.
- *
- * How would you ensure that every place that used these types of bindings was bound to a value that
- * was sanitized by your library (or returned as safe for rendering by your server?) How can you
- * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
- * properties/fields and forgot to update the binding to the sanitized value?
- *
- * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
- * determine that something explicitly says it's safe to use a value for binding in that
- * context. You can then audit your code (a simple grep would do) to ensure that this is only done
- * for those values that you can easily tell are safe - because they were received from your server,
- * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
- * allowing only the files in a specific directory to do this. Ensuring that the internal API
- * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
- *
- * In the case of AngularJS' SCE service, one uses {@link ng.$sce#methods_trustAs $sce.trustAs}
- * (and shorthand methods such as {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}, etc.) to
- * obtain values that will be accepted by SCE / privileged contexts.
- *
- *
- * ## How does it work?
- *
- * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#methods_getTrusted
- * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
- * ng.$sce#methods_parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
- * {@link ng.$sce#methods_getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
- *
- * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
- * ng.$sce#methods_parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
- * simplified):
- *
- *
- *
- * ## Impact on loading templates
- *
- * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
- * `templateUrl`'s specified by {@link guide/directive directives}.
- *
- * By default, Angular only loads templates from the same domain and protocol as the application
- * document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
- * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
- * protocols, you may either either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist
- * them} or {@link ng.$sce#methods_trustAsResourceUrl wrap it} into a trusted value.
- *
- * *Please note*:
- * The browser's
- * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
- * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)}
- * policy apply in addition to this and may further restrict whether the template is successfully
- * loaded. This means that without the right CORS policy, loading templates from a different domain
- * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
- * browsers.
- *
- * ## This feels like too much overhead for the developer?
- *
- * It's important to remember that SCE only applies to interpolation expressions.
- *
- * If your expressions are constant literals, they're automatically trusted and you don't need to
- * call `$sce.trustAs` on them. (e.g.
- * ``) just works.
- *
- * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
- * through {@link ng.$sce#methods_getTrusted $sce.getTrusted}. SCE doesn't play a role here.
- *
- * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
- * templates in `ng-include` from your application's domain without having to even know about SCE.
- * It blocks loading templates from other domains or loading templates over http from an https
- * served document. You can change these by setting your own custom {@link
- * ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelists} and {@link
- * ng.$sceDelegateProvider#methods_resourceUrlBlacklist blacklists} for matching such URLs.
- *
- * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
- * application that's secure and can be audited to verify that with much more ease than bolting
- * security onto an application later.
- *
- *
- * ## What trusted context types are supported?
- *
- * | Context | Notes |
- * |---------------------|----------------|
- * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. |
- * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
- * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (` Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
- * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
- *
- * ## Format of items in {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist Blacklist}
- *
- * Each element in these arrays must be one of the following:
- *
- * - **'self'**
- * - The special **string**, `'self'`, can be used to match against all URLs of the **same
- * domain** as the application document using the **same protocol**.
- * - **String** (except the special value `'self'`)
- * - The string is matched against the full *normalized / absolute URL* of the resource
- * being tested (substring matches are not good enough.)
- * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
- * match themselves.
- * - `*`: matches zero or more occurances of any character other than one of the following 6
- * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
- * in a whitelist.
- * - `**`: matches zero or more occurances of *any* character. As such, it's not
- * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
- * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
- * not have been the intention.) It's usage at the very end of the path is ok. (e.g.
- * http://foo.example.com/templates/**).
- * - **RegExp** (*see caveat below*)
- * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
- * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
- * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
- * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
- * small number of cases. A `.` character in the regex used when matching the scheme or a
- * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
- * is highly recommended to use the string patterns and only fall back to regular expressions
- * if they as a last resort.
- * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
- * matched against the **entire** *normalized / absolute URL* of the resource being tested
- * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
- * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
- * - If you are generating your Javascript from some other templating engine (not
- * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
- * remember to escape your regular expression (and be aware that you might need more than
- * one level of escaping depending on your templating engine and the way you interpolated
- * the value.) Do make use of your platform's escaping mechanism as it might be good
- * enough before coding your own. e.g. Ruby has
- * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
- * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
- * Javascript lacks a similar built in function for escaping. Take a look at Google
- * Closure library's [goog.string.regExpEscape(s)](
- * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
- *
- * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
- *
- * ## Show me an example using SCE.
- *
- * @example
-
-
-
-
- User comments
- By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
- $sanitize is available. If $sanitize isn't available, this results in an error instead of an
- exploit.
-
-
- {{userComment.name}}:
-
-
-
-
-
-
-
-
- var mySceApp = angular.module('mySceApp', ['ngSanitize']);
-
- mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
- var self = this;
- $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
- self.userComments = userComments;
- });
- self.explicitlyTrustedHtml = $sce.trustAsHtml(
- 'Hover over this text.');
- });
-
-
-
-[
- { "name": "Alice",
- "htmlComment":
- "Is anyone reading this?"
- },
- { "name": "Bob",
- "htmlComment": "Yes! Am I the only other one?"
- }
-]
-
-
-
- describe('SCE doc demo', function() {
- it('should sanitize untrusted values', function() {
- expect(element('.htmlComment').html()).toBe('Is anyone reading this?');
- });
- it('should NOT sanitize explicitly trusted values', function() {
- expect(element('#explicitlyTrustedHtml').html()).toBe(
- 'Hover over this text.');
- });
- });
-
-
- *
- *
- *
- * ## Can I disable SCE completely?
- *
- * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
- * for little coding overhead. It will be much harder to take an SCE disabled application and
- * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
- * for cases where you have a lot of existing code that was written before SCE was introduced and
- * you're migrating them a module at a time.
- *
- * That said, here's how you can completely disable SCE:
- *
- *
- * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
- * // Completely disable SCE. For demonstration purposes only!
- * // Do not use in new projects.
- * $sceProvider.enabled(false);
- * });
- *
- *
- */
-/* jshint maxlen: 100 */
-
-function $SceProvider() {
- var enabled = true;
-
- /**
- * @ngdoc function
- * @name ng.sceProvider#enabled
- * @methodOf ng.$sceProvider
- * @function
- *
- * @param {boolean=} value If provided, then enables/disables SCE.
- * @return {boolean} true if SCE is enabled, false otherwise.
- *
- * @description
- * Enables/disables SCE and returns the current value.
- */
- this.enabled = function (value) {
- if (arguments.length) {
- enabled = !!value;
- }
- return enabled;
- };
-
-
- /* Design notes on the default implementation for SCE.
- *
- * The API contract for the SCE delegate
- * -------------------------------------
- * The SCE delegate object must provide the following 3 methods:
- *
- * - trustAs(contextEnum, value)
- * This method is used to tell the SCE service that the provided value is OK to use in the
- * contexts specified by contextEnum. It must return an object that will be accepted by
- * getTrusted() for a compatible contextEnum and return this value.
- *
- * - valueOf(value)
- * For values that were not produced by trustAs(), return them as is. For values that were
- * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
- * trustAs is wrapping the given values into some type, this operation unwraps it when given
- * such a value.
- *
- * - getTrusted(contextEnum, value)
- * This function should return the a value that is safe to use in the context specified by
- * contextEnum or throw and exception otherwise.
- *
- * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
- * opaque or wrapped in some holder object. That happens to be an implementation detail. For
- * instance, an implementation could maintain a registry of all trusted objects by context. In
- * such a case, trustAs() would return the same object that was passed in. getTrusted() would
- * return the same object passed in if it was found in the registry under a compatible context or
- * throw an exception otherwise. An implementation might only wrap values some of the time based
- * on some criteria. getTrusted() might return a value and not throw an exception for special
- * constants or objects even if not wrapped. All such implementations fulfill this contract.
- *
- *
- * A note on the inheritance model for SCE contexts
- * ------------------------------------------------
- * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
- * is purely an implementation details.
- *
- * The contract is simply this:
- *
- * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
- * will also succeed.
- *
- * Inheritance happens to capture this in a natural way. In some future, we
- * may not use inheritance anymore. That is OK because no code outside of
- * sce.js and sceSpecs.js would need to be aware of this detail.
- */
-
- this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
- $parse, $sniffer, $sceDelegate) {
- // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
- // the "expression(javascript expression)" syntax which is insecure.
- if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
- throw $sceMinErr('iequirks',
- 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
- 'mode. You can fix this by adding the text to the top of your HTML ' +
- 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
- }
-
- var sce = copy(SCE_CONTEXTS);
-
- /**
- * @ngdoc function
- * @name ng.sce#isEnabled
- * @methodOf ng.$sce
- * @function
- *
- * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
- * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
- *
- * @description
- * Returns a boolean indicating if SCE is enabled.
- */
- sce.isEnabled = function () {
- return enabled;
- };
- sce.trustAs = $sceDelegate.trustAs;
- sce.getTrusted = $sceDelegate.getTrusted;
- sce.valueOf = $sceDelegate.valueOf;
-
- if (!enabled) {
- sce.trustAs = sce.getTrusted = function(type, value) { return value; };
- sce.valueOf = identity;
- }
-
- /**
- * @ngdoc method
- * @name ng.$sce#parse
- * @methodOf ng.$sce
- *
- * @description
- * Converts Angular {@link guide/expression expression} into a function. This is like {@link
- * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
- * wraps the expression in a call to {@link ng.$sce#methods_getTrusted $sce.getTrusted(*type*,
- * *result*)}
- *
- * @param {string} type The kind of SCE context in which this result will be used.
- * @param {string} expression String expression to compile.
- * @returns {function(context, locals)} a function which represents the compiled expression:
- *
- * * `context` – `{object}` – an object against which any expressions embedded in the strings
- * are evaluated against (typically a scope object).
- * * `locals` – `{object=}` – local variables context object, useful for overriding values in
- * `context`.
- */
- sce.parseAs = function sceParseAs(type, expr) {
- var parsed = $parse(expr);
- if (parsed.literal && parsed.constant) {
- return parsed;
- } else {
- return function sceParseAsTrusted(self, locals) {
- return sce.getTrusted(type, parsed(self, locals));
- };
- }
- };
-
- /**
- * @ngdoc method
- * @name ng.$sce#trustAs
- * @methodOf ng.$sce
- *
- * @description
- * Delegates to {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}. As such,
- * returns an objectthat is trusted by angular for use in specified strict contextual
- * escaping contexts (such as ng-html-bind-unsafe, ng-include, any src attribute
- * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
- * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
- * escaping.
- *
- * @param {string} type The kind of context in which this value is safe for use. e.g. url,
- * resource_url, html, js and css.
- * @param {*} value The value that that should be considered trusted/safe.
- * @returns {*} A value that can be used to stand in for the provided `value` in places
- * where Angular expects a $sce.trustAs() return value.
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#trustAsHtml
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.trustAsHtml(value)` →
- * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
- *
- * @param {*} value The value to trustAs.
- * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedHtml
- * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
- * only accept expressions that are either literal constants or are the
- * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#trustAsUrl
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.trustAsUrl(value)` →
- * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.URL, value)`}
- *
- * @param {*} value The value to trustAs.
- * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedUrl
- * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
- * only accept expressions that are either literal constants or are the
- * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#trustAsResourceUrl
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.trustAsResourceUrl(value)` →
- * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
- *
- * @param {*} value The value to trustAs.
- * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedResourceUrl
- * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
- * only accept expressions that are either literal constants or are the return
- * value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#trustAsJs
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.trustAsJs(value)` →
- * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.JS, value)`}
- *
- * @param {*} value The value to trustAs.
- * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedJs
- * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
- * only accept expressions that are either literal constants or are the
- * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#getTrusted
- * @methodOf ng.$sce
- *
- * @description
- * Delegates to {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted`}. As such,
- * takes the result of a {@link ng.$sce#methods_trustAs `$sce.trustAs`}() call and returns the
- * originally supplied value if the queried context type is a supertype of the created type.
- * If this condition isn't satisfied, throws an exception.
- *
- * @param {string} type The kind of context in which this value is to be used.
- * @param {*} maybeTrusted The result of a prior {@link ng.$sce#methods_trustAs `$sce.trustAs`}
- * call.
- * @returns {*} The value the was originally provided to
- * {@link ng.$sce#methods_trustAs `$sce.trustAs`} if valid in this context.
- * Otherwise, throws an exception.
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#getTrustedHtml
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.getTrustedHtml(value)` →
- * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
- *
- * @param {*} value The value to pass to `$sce.getTrusted`.
- * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#getTrustedCss
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.getTrustedCss(value)` →
- * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
- *
- * @param {*} value The value to pass to `$sce.getTrusted`.
- * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#getTrustedUrl
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.getTrustedUrl(value)` →
- * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
- *
- * @param {*} value The value to pass to `$sce.getTrusted`.
- * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#getTrustedResourceUrl
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
- * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
- *
- * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
- * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#getTrustedJs
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.getTrustedJs(value)` →
- * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
- *
- * @param {*} value The value to pass to `$sce.getTrusted`.
- * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#parseAsHtml
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.parseAsHtml(expression string)` →
- * {@link ng.$sce#methods_parse `$sce.parseAs($sce.HTML, value)`}
- *
- * @param {string} expression String expression to compile.
- * @returns {function(context, locals)} a function which represents the compiled expression:
- *
- * * `context` – `{object}` – an object against which any expressions embedded in the strings
- * are evaluated against (typically a scope object).
- * * `locals` – `{object=}` – local variables context object, useful for overriding values in
- * `context`.
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#parseAsCss
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.parseAsCss(value)` →
- * {@link ng.$sce#methods_parse `$sce.parseAs($sce.CSS, value)`}
- *
- * @param {string} expression String expression to compile.
- * @returns {function(context, locals)} a function which represents the compiled expression:
- *
- * * `context` – `{object}` – an object against which any expressions embedded in the strings
- * are evaluated against (typically a scope object).
- * * `locals` – `{object=}` – local variables context object, useful for overriding values in
- * `context`.
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#parseAsUrl
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.parseAsUrl(value)` →
- * {@link ng.$sce#methods_parse `$sce.parseAs($sce.URL, value)`}
- *
- * @param {string} expression String expression to compile.
- * @returns {function(context, locals)} a function which represents the compiled expression:
- *
- * * `context` – `{object}` – an object against which any expressions embedded in the strings
- * are evaluated against (typically a scope object).
- * * `locals` – `{object=}` – local variables context object, useful for overriding values in
- * `context`.
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#parseAsResourceUrl
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.parseAsResourceUrl(value)` →
- * {@link ng.$sce#methods_parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
- *
- * @param {string} expression String expression to compile.
- * @returns {function(context, locals)} a function which represents the compiled expression:
- *
- * * `context` – `{object}` – an object against which any expressions embedded in the strings
- * are evaluated against (typically a scope object).
- * * `locals` – `{object=}` – local variables context object, useful for overriding values in
- * `context`.
- */
-
- /**
- * @ngdoc method
- * @name ng.$sce#parseAsJs
- * @methodOf ng.$sce
- *
- * @description
- * Shorthand method. `$sce.parseAsJs(value)` →
- * {@link ng.$sce#methods_parse `$sce.parseAs($sce.JS, value)`}
- *
- * @param {string} expression String expression to compile.
- * @returns {function(context, locals)} a function which represents the compiled expression:
- *
- * * `context` – `{object}` – an object against which any expressions embedded in the strings
- * are evaluated against (typically a scope object).
- * * `locals` – `{object=}` – local variables context object, useful for overriding values in
- * `context`.
- */
-
- // Shorthand delegations.
- var parse = sce.parseAs,
- getTrusted = sce.getTrusted,
- trustAs = sce.trustAs;
-
- forEach(SCE_CONTEXTS, function (enumValue, name) {
- var lName = lowercase(name);
- sce[camelCase("parse_as_" + lName)] = function (expr) {
- return parse(enumValue, expr);
- };
- sce[camelCase("get_trusted_" + lName)] = function (value) {
- return getTrusted(enumValue, value);
- };
- sce[camelCase("trust_as_" + lName)] = function (value) {
- return trustAs(enumValue, value);
- };
- });
-
- return sce;
- }];
-}
-
-/**
- * !!! This is an undocumented "private" service !!!
- *
- * @name ng.$sniffer
- * @requires $window
- * @requires $document
- *
- * @property {boolean} history Does the browser support html5 history api ?
- * @property {boolean} hashchange Does the browser support hashchange event ?
- * @property {boolean} transitions Does the browser support CSS transition events ?
- * @property {boolean} animations Does the browser support CSS animation events ?
- *
- * @description
- * This is very simple implementation of testing browser's features.
- */
-function $SnifferProvider() {
- this.$get = ['$window', '$document', function($window, $document) {
- var eventSupport = {},
- android =
- int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
- boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
- document = $document[0] || {},
- documentMode = document.documentMode,
- vendorPrefix,
- vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
- bodyStyle = document.body && document.body.style,
- transitions = false,
- animations = false,
- match;
-
- if (bodyStyle) {
- for(var prop in bodyStyle) {
- if(match = vendorRegex.exec(prop)) {
- vendorPrefix = match[0];
- vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
- break;
- }
- }
-
- if(!vendorPrefix) {
- vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
- }
-
- transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
- animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
-
- if (android && (!transitions||!animations)) {
- transitions = isString(document.body.style.webkitTransition);
- animations = isString(document.body.style.webkitAnimation);
- }
- }
-
-
- return {
- // Android has history.pushState, but it does not update location correctly
- // so let's not use the history API at all.
- // http://code.google.com/p/android/issues/detail?id=17471
- // https://github.com/angular/angular.js/issues/904
-
- // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
- // so let's not use the history API also
- // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
- // jshint -W018
- history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
- // jshint +W018
- hashchange: 'onhashchange' in $window &&
- // IE8 compatible mode lies
- (!documentMode || documentMode > 7),
- hasEvent: function(event) {
- // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
- // it. In particular the event is not fired when backspace or delete key are pressed or
- // when cut operation is performed.
- if (event == 'input' && msie == 9) return false;
-
- if (isUndefined(eventSupport[event])) {
- var divElm = document.createElement('div');
- eventSupport[event] = 'on' + event in divElm;
- }
-
- return eventSupport[event];
- },
- csp: csp(),
- vendorPrefix: vendorPrefix,
- transitions : transitions,
- animations : animations,
- android: android,
- msie : msie,
- msieDocumentMode: documentMode
- };
- }];
-}
-
-function $TimeoutProvider() {
- this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
- function($rootScope, $browser, $q, $exceptionHandler) {
- var deferreds = {};
-
-
- /**
- * @ngdoc function
- * @name ng.$timeout
- * @requires $browser
- *
- * @description
- * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
- * block and delegates any exceptions to
- * {@link ng.$exceptionHandler $exceptionHandler} service.
- *
- * The return value of registering a timeout function is a promise, which will be resolved when
- * the timeout is reached and the timeout function is executed.
- *
- * To cancel a timeout request, call `$timeout.cancel(promise)`.
- *
- * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
- * synchronously flush the queue of deferred functions.
- *
- * @param {function()} fn A function, whose execution should be delayed.
- * @param {number=} [delay=0] Delay in milliseconds.
- * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
- * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
- * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
- * promise will be resolved with is the return value of the `fn` function.
- *
- */
- function timeout(fn, delay, invokeApply) {
- var deferred = $q.defer(),
- promise = deferred.promise,
- skipApply = (isDefined(invokeApply) && !invokeApply),
- timeoutId;
-
- timeoutId = $browser.defer(function() {
- try {
- deferred.resolve(fn());
- } catch(e) {
- deferred.reject(e);
- $exceptionHandler(e);
- }
- finally {
- delete deferreds[promise.$$timeoutId];
- }
-
- if (!skipApply) $rootScope.$apply();
- }, delay);
-
- promise.$$timeoutId = timeoutId;
- deferreds[timeoutId] = deferred;
-
- return promise;
- }
-
-
- /**
- * @ngdoc function
- * @name ng.$timeout#cancel
- * @methodOf ng.$timeout
- *
- * @description
- * Cancels a task associated with the `promise`. As a result of this, the promise will be
- * resolved with a rejection.
- *
- * @param {Promise=} promise Promise returned by the `$timeout` function.
- * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
- * canceled.
- */
- timeout.cancel = function(promise) {
- if (promise && promise.$$timeoutId in deferreds) {
- deferreds[promise.$$timeoutId].reject('canceled');
- delete deferreds[promise.$$timeoutId];
- return $browser.defer.cancel(promise.$$timeoutId);
- }
- return false;
- };
-
- return timeout;
- }];
-}
-
-// NOTE: The usage of window and document instead of $window and $document here is
-// deliberate. This service depends on the specific behavior of anchor nodes created by the
-// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
-// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
-// doesn't know about mocked locations and resolves URLs to the real document - which is
-// exactly the behavior needed here. There is little value is mocking these out for this
-// service.
-var urlParsingNode = document.createElement("a");
-var originUrl = urlResolve(window.location.href, true);
-
-
-/**
- *
- * Implementation Notes for non-IE browsers
- * ----------------------------------------
- * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
- * results both in the normalizing and parsing of the URL. Normalizing means that a relative
- * URL will be resolved into an absolute URL in the context of the application document.
- * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
- * properties are all populated to reflect the normalized URL. This approach has wide
- * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
- * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
- *
- * Implementation Notes for IE
- * ---------------------------
- * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
- * browsers. However, the parsed components will not be set if the URL assigned did not specify
- * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
- * work around that by performing the parsing in a 2nd step by taking a previously normalized
- * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
- * properties such as protocol, hostname, port, etc.
- *
- * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
- * uses the inner HTML approach to assign the URL as part of an HTML snippet -
- * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
- * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
- * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
- * method and IE < 8 is unsupported.
- *
- * References:
- * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
- * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
- * http://url.spec.whatwg.org/#urlutils
- * https://github.com/angular/angular.js/pull/2902
- * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
- *
- * @function
- * @param {string} url The URL to be parsed.
- * @description Normalizes and parses a URL.
- * @returns {object} Returns the normalized URL as a dictionary.
- *
- * | member name | Description |
- * |---------------|----------------|
- * | href | A normalized version of the provided URL if it was not an absolute URL |
- * | protocol | The protocol including the trailing colon |
- * | host | The host and port (if the port is non-default) of the normalizedUrl |
- * | search | The search params, minus the question mark |
- * | hash | The hash string, minus the hash symbol
- * | hostname | The hostname
- * | port | The port, without ":"
- * | pathname | The pathname, beginning with "/"
- *
- */
-function urlResolve(url, base) {
- var href = url;
-
- if (msie) {
- // Normalize before parse. Refer Implementation Notes on why this is
- // done in two steps on IE.
- urlParsingNode.setAttribute("href", href);
- href = urlParsingNode.href;
- }
-
- urlParsingNode.setAttribute('href', href);
-
- // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
- return {
- href: urlParsingNode.href,
- protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
- host: urlParsingNode.host,
- search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
- hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
- hostname: urlParsingNode.hostname,
- port: urlParsingNode.port,
- pathname: (urlParsingNode.pathname.charAt(0) === '/')
- ? urlParsingNode.pathname
- : '/' + urlParsingNode.pathname
- };
-}
-
-/**
- * Parse a request URL and determine whether this is a same-origin request as the application document.
- *
- * @param {string|object} requestUrl The url of the request as a string that will be resolved
- * or a parsed URL object.
- * @returns {boolean} Whether the request is for the same origin as the application document.
- */
-function urlIsSameOrigin(requestUrl) {
- var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
- return (parsed.protocol === originUrl.protocol &&
- parsed.host === originUrl.host);
-}
-
-/**
- * @ngdoc object
- * @name ng.$window
- *
- * @description
- * A reference to the browser's `window` object. While `window`
- * is globally available in JavaScript, it causes testability problems, because
- * it is a global variable. In angular we always refer to it through the
- * `$window` service, so it may be overridden, removed or mocked for testing.
- *
- * Expressions, like the one defined for the `ngClick` directive in the example
- * below, are evaluated with respect to the current scope. Therefore, there is
- * no risk of inadvertently coding in a dependency on a global value in such an
- * expression.
- *
- * @example
-
-
-
-
-
-
-
-
-
- it('should display the greeting in the input box', function() {
- input('greeting').enter('Hello, E2E Tests');
- // If we click the button it will block the test runner
- // element(':button').click();
- });
-
-
- */
-function $WindowProvider(){
- this.$get = valueFn(window);
-}
-
-/**
- * @ngdoc object
- * @name ng.$filterProvider
- * @description
- *
- * Filters are just functions which transform input to an output. However filters need to be
- * Dependency Injected. To achieve this a filter definition consists of a factory function which is
- * annotated with dependencies and is responsible for creating a filter function.
- *
- *
- * // Filter registration
- * function MyModule($provide, $filterProvider) {
- * // create a service to demonstrate injection (not always needed)
- * $provide.value('greet', function(name){
- * return 'Hello ' + name + '!';
- * });
- *
- * // register a filter factory which uses the
- * // greet service to demonstrate DI.
- * $filterProvider.register('greet', function(greet){
- * // return the filter function which uses the greet service
- * // to generate salutation
- * return function(text) {
- * // filters need to be forgiving so check input validity
- * return text && greet(text) || text;
- * };
- * });
- * }
- *
- *
- * The filter function is registered with the `$injector` under the filter name suffix with
- * `Filter`.
- *
- *
- *
- *
- * For more information about how angular filters work, and how to create your own filters, see
- * {@link guide/filter Filters} in the Angular Developer Guide.
- */
-/**
- * @ngdoc method
- * @name ng.$filterProvider#register
- * @methodOf ng.$filterProvider
- * @description
- * Register filter factory function.
- *
- * @param {String} name Name of the filter.
- * @param {function} fn The filter factory function which is injectable.
- */
-
-
-/**
- * @ngdoc function
- * @name ng.$filter
- * @function
- * @description
- * Filters are used for formatting data displayed to the user.
- *
- * The general syntax in templates is as follows:
- *
- * {{ expression [| filter_name[:parameter_value] ... ] }}
- *
- * @param {String} name Name of the filter function to retrieve
- * @return {Function} the filter function
- */
-$FilterProvider.$inject = ['$provide'];
-function $FilterProvider($provide) {
- var suffix = 'Filter';
-
- /**
- * @ngdoc function
- * @name ng.$controllerProvider#register
- * @methodOf ng.$controllerProvider
- * @param {string|Object} name Name of the filter function, or an object map of filters where
- * the keys are the filter names and the values are the filter factories.
- * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
- * of the registered filter instances.
- */
- function register(name, factory) {
- if(isObject(name)) {
- var filters = {};
- forEach(name, function(filter, key) {
- filters[key] = register(key, filter);
- });
- return filters;
- } else {
- return $provide.factory(name + suffix, factory);
- }
- }
- this.register = register;
-
- this.$get = ['$injector', function($injector) {
- return function(name) {
- return $injector.get(name + suffix);
- };
- }];
-
- ////////////////////////////////////////
-
- /* global
- currencyFilter: false,
- dateFilter: false,
- filterFilter: false,
- jsonFilter: false,
- limitToFilter: false,
- lowercaseFilter: false,
- numberFilter: false,
- orderByFilter: false,
- uppercaseFilter: false,
- */
-
- register('currency', currencyFilter);
- register('date', dateFilter);
- register('filter', filterFilter);
- register('json', jsonFilter);
- register('limitTo', limitToFilter);
- register('lowercase', lowercaseFilter);
- register('number', numberFilter);
- register('orderBy', orderByFilter);
- register('uppercase', uppercaseFilter);
-}
-
-/**
- * @ngdoc filter
- * @name ng.filter:filter
- * @function
- *
- * @description
- * Selects a subset of items from `array` and returns it as a new array.
- *
- * @param {Array} array The source array.
- * @param {string|Object|function()} expression The predicate to be used for selecting items from
- * `array`.
- *
- * Can be one of:
- *
- * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
- * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
- * will be returned. The predicate can be negated by prefixing the string with `!`.
- *
- * - `Object`: A pattern object can be used to filter specific properties on objects contained
- * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
- * which have property `name` containing "M" and property `phone` containing "1". A special
- * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
- * property of the object. That's equivalent to the simple substring match with a `string`
- * as described above.
- *
- * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
- * called for each element of `array`. The final result is an array of those elements that
- * the predicate returned true for.
- *
- * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
- * determining if the expected value (from the filter expression) and actual value (from
- * the object in the array) should be considered a match.
- *
- * Can be one of:
- *
- * - `function(actual, expected)`:
- * The function will be given the object value and the predicate value to compare and
- * should return true if the item should be included in filtered result.
- *
- * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
- * this is essentially strict comparison of expected and actual.
- *
- * - `false|undefined`: A short hand for a function which will look for a substring match in case
- * insensitive way.
- *
- * @example
-
-
-
-
- Search:
-
-
Name
Phone
-
-
{{friend.name}}
-
{{friend.phone}}
-
-
-
- Any:
- Name only
- Phone only
- Equality
-
-
Name
Phone
-
-
{{friend.name}}
-
{{friend.phone}}
-
-
-
-
- it('should search across all fields when filtering with a string', function() {
- input('searchText').enter('m');
- expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
- toEqual(['Mary', 'Mike', 'Adam']);
-
- input('searchText').enter('76');
- expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
- toEqual(['John', 'Julie']);
- });
-
- it('should search in specific fields when filtering with a predicate object', function() {
- input('search.$').enter('i');
- expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
- toEqual(['Mary', 'Mike', 'Julie', 'Juliette']);
- });
- it('should use a equal comparison when comparator is true', function() {
- input('search.name').enter('Julie');
- input('strict').check();
- expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
- toEqual(['Julie']);
- });
-
-
- */
-function filterFilter() {
- return function(array, expression, comparator) {
- if (!isArray(array)) return array;
-
- var comparatorType = typeof(comparator),
- predicates = [];
-
- predicates.check = function(value) {
- for (var j = 0; j < predicates.length; j++) {
- if(!predicates[j](value)) {
- return false;
- }
- }
- return true;
- };
-
- if (comparatorType !== 'function') {
- if (comparatorType === 'boolean' && comparator) {
- comparator = function(obj, text) {
- return angular.equals(obj, text);
- };
- } else {
- comparator = function(obj, text) {
- text = (''+text).toLowerCase();
- return (''+obj).toLowerCase().indexOf(text) > -1;
- };
- }
- }
-
- var search = function(obj, text){
- if (typeof text == 'string' && text.charAt(0) === '!') {
- return !search(obj, text.substr(1));
- }
- switch (typeof obj) {
- case "boolean":
- case "number":
- case "string":
- return comparator(obj, text);
- case "object":
- switch (typeof text) {
- case "object":
- return comparator(obj, text);
- default:
- for ( var objKey in obj) {
- if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
- return true;
- }
- }
- break;
- }
- return false;
- case "array":
- for ( var i = 0; i < obj.length; i++) {
- if (search(obj[i], text)) {
- return true;
- }
- }
- return false;
- default:
- return false;
- }
- };
- switch (typeof expression) {
- case "boolean":
- case "number":
- case "string":
- // Set up expression object and fall through
- expression = {$:expression};
- // jshint -W086
- case "object":
- // jshint +W086
- for (var key in expression) {
- (function(path) {
- if (typeof expression[path] == 'undefined') return;
- predicates.push(function(value) {
- return search(path == '$' ? value : getter(value, path), expression[path]);
- });
- })(key);
- }
- break;
- case 'function':
- predicates.push(expression);
- break;
- default:
- return array;
- }
- var filtered = [];
- for ( var j = 0; j < array.length; j++) {
- var value = array[j];
- if (predicates.check(value)) {
- filtered.push(value);
- }
- }
- return filtered;
- };
-}
-
-/**
- * @ngdoc filter
- * @name ng.filter:currency
- * @function
- *
- * @description
- * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
- * symbol for current locale is used.
- *
- * @param {number} amount Input to filter.
- * @param {string=} symbol Currency symbol or identifier to be displayed.
- * @returns {string} Formatted number.
- *
- *
- * @example
-
-
-
-
-
-
- it('should init with 1234.56', function() {
- expect(binding('amount | currency')).toBe('$1,234.56');
- expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
- });
- it('should update', function() {
- input('amount').enter('-1234');
- expect(binding('amount | currency')).toBe('($1,234.00)');
- expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
- });
-
-
- */
-currencyFilter.$inject = ['$locale'];
-function currencyFilter($locale) {
- var formats = $locale.NUMBER_FORMATS;
- return function(amount, currencySymbol){
- if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
- return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
- replace(/\u00A4/g, currencySymbol);
- };
-}
-
-/**
- * @ngdoc filter
- * @name ng.filter:number
- * @function
- *
- * @description
- * Formats a number as text.
- *
- * If the input is not a number an empty string is returned.
- *
- * @param {number|string} number Number to format.
- * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
- * If this is not provided then the fraction size is computed from the current locale's number
- * formatting pattern. In the case of the default locale, it will be 3.
- * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
- *
- * @example
-
-
-
-
-
-
- it('should format numbers', function() {
- expect(binding('val | number')).toBe('1,234.568');
- expect(binding('val | number:0')).toBe('1,235');
- expect(binding('-val | number:4')).toBe('-1,234.5679');
- });
-
- it('should update', function() {
- input('val').enter('3374.333');
- expect(binding('val | number')).toBe('3,374.333');
- expect(binding('val | number:0')).toBe('3,374');
- expect(binding('-val | number:4')).toBe('-3,374.3330');
- });
-
-
- */
-
-
-numberFilter.$inject = ['$locale'];
-function numberFilter($locale) {
- var formats = $locale.NUMBER_FORMATS;
- return function(number, fractionSize) {
- return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
- fractionSize);
- };
-}
-
-var DECIMAL_SEP = '.';
-function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
- if (isNaN(number) || !isFinite(number)) return '';
-
- var isNegative = number < 0;
- number = Math.abs(number);
- var numStr = number + '',
- formatedText = '',
- parts = [];
-
- var hasExponent = false;
- if (numStr.indexOf('e') !== -1) {
- var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
- if (match && match[2] == '-' && match[3] > fractionSize + 1) {
- numStr = '0';
- } else {
- formatedText = numStr;
- hasExponent = true;
- }
- }
-
- if (!hasExponent) {
- var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
-
- // determine fractionSize if it is not specified
- if (isUndefined(fractionSize)) {
- fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
- }
-
- var pow = Math.pow(10, fractionSize);
- number = Math.round(number * pow) / pow;
- var fraction = ('' + number).split(DECIMAL_SEP);
- var whole = fraction[0];
- fraction = fraction[1] || '';
-
- var i, pos = 0,
- lgroup = pattern.lgSize,
- group = pattern.gSize;
-
- if (whole.length >= (lgroup + group)) {
- pos = whole.length - lgroup;
- for (i = 0; i < pos; i++) {
- if ((pos - i)%group === 0 && i !== 0) {
- formatedText += groupSep;
- }
- formatedText += whole.charAt(i);
- }
- }
-
- for (i = pos; i < whole.length; i++) {
- if ((whole.length - i)%lgroup === 0 && i !== 0) {
- formatedText += groupSep;
- }
- formatedText += whole.charAt(i);
- }
-
- // format fraction part.
- while(fraction.length < fractionSize) {
- fraction += '0';
- }
-
- if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
- } else {
-
- if (fractionSize > 0 && number > -1 && number < 1) {
- formatedText = number.toFixed(fractionSize);
- }
- }
-
- parts.push(isNegative ? pattern.negPre : pattern.posPre);
- parts.push(formatedText);
- parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
- return parts.join('');
-}
-
-function padNumber(num, digits, trim) {
- var neg = '';
- if (num < 0) {
- neg = '-';
- num = -num;
- }
- num = '' + num;
- while(num.length < digits) num = '0' + num;
- if (trim)
- num = num.substr(num.length - digits);
- return neg + num;
-}
-
-
-function dateGetter(name, size, offset, trim) {
- offset = offset || 0;
- return function(date) {
- var value = date['get' + name]();
- if (offset > 0 || value > -offset)
- value += offset;
- if (value === 0 && offset == -12 ) value = 12;
- return padNumber(value, size, trim);
- };
-}
-
-function dateStrGetter(name, shortForm) {
- return function(date, formats) {
- var value = date['get' + name]();
- var get = uppercase(shortForm ? ('SHORT' + name) : name);
-
- return formats[get][value];
- };
-}
-
-function timeZoneGetter(date) {
- var zone = -1 * date.getTimezoneOffset();
- var paddedZone = (zone >= 0) ? "+" : "";
-
- paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
- padNumber(Math.abs(zone % 60), 2);
-
- return paddedZone;
-}
-
-function ampmGetter(date, formats) {
- return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
-}
-
-var DATE_FORMATS = {
- yyyy: dateGetter('FullYear', 4),
- yy: dateGetter('FullYear', 2, 0, true),
- y: dateGetter('FullYear', 1),
- MMMM: dateStrGetter('Month'),
- MMM: dateStrGetter('Month', true),
- MM: dateGetter('Month', 2, 1),
- M: dateGetter('Month', 1, 1),
- dd: dateGetter('Date', 2),
- d: dateGetter('Date', 1),
- HH: dateGetter('Hours', 2),
- H: dateGetter('Hours', 1),
- hh: dateGetter('Hours', 2, -12),
- h: dateGetter('Hours', 1, -12),
- mm: dateGetter('Minutes', 2),
- m: dateGetter('Minutes', 1),
- ss: dateGetter('Seconds', 2),
- s: dateGetter('Seconds', 1),
- // while ISO 8601 requires fractions to be prefixed with `.` or `,`
- // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
- sss: dateGetter('Milliseconds', 3),
- EEEE: dateStrGetter('Day'),
- EEE: dateStrGetter('Day', true),
- a: ampmGetter,
- Z: timeZoneGetter
-};
-
-var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
- NUMBER_STRING = /^\-?\d+$/;
-
-/**
- * @ngdoc filter
- * @name ng.filter:date
- * @function
- *
- * @description
- * Formats `date` to a string based on the requested `format`.
- *
- * `format` string can be composed of the following elements:
- *
- * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
- * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
- * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
- * * `'MMMM'`: Month in year (January-December)
- * * `'MMM'`: Month in year (Jan-Dec)
- * * `'MM'`: Month in year, padded (01-12)
- * * `'M'`: Month in year (1-12)
- * * `'dd'`: Day in month, padded (01-31)
- * * `'d'`: Day in month (1-31)
- * * `'EEEE'`: Day in Week,(Sunday-Saturday)
- * * `'EEE'`: Day in Week, (Sun-Sat)
- * * `'HH'`: Hour in day, padded (00-23)
- * * `'H'`: Hour in day (0-23)
- * * `'hh'`: Hour in am/pm, padded (01-12)
- * * `'h'`: Hour in am/pm, (1-12)
- * * `'mm'`: Minute in hour, padded (00-59)
- * * `'m'`: Minute in hour (0-59)
- * * `'ss'`: Second in minute, padded (00-59)
- * * `'s'`: Second in minute (0-59)
- * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
- * * `'a'`: am/pm marker
- * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
- *
- * `format` string can also be one of the following predefined
- * {@link guide/i18n localizable formats}:
- *
- * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
- * (e.g. Sep 3, 2010 12:05:08 pm)
- * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
- * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
- * (e.g. Friday, September 3, 2010)
- * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
- * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
- * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
- * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
- * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
- *
- * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
- * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
- * (e.g. `"h 'o''clock'"`).
- *
- * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
- * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
- * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
- * specified in the string input, the time is considered to be in the local timezone.
- * @param {string=} format Formatting rules (see Description). If not specified,
- * `mediumDate` is used.
- * @returns {string} Formatted string or the input if input is not recognized as date/millis.
- *
- * @example
-
-
- {{1288323623006 | date:'medium'}}:
- {{1288323623006 | date:'medium'}}
- {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}:
- {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
- {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}:
- {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
-
-
- it('should format date', function() {
- expect(binding("1288323623006 | date:'medium'")).
- toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
- expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
- toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
- expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
- toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
- });
-
-
- */
-dateFilter.$inject = ['$locale'];
-function dateFilter($locale) {
-
-
- var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
- // 1 2 3 4 5 6 7 8 9 10 11
- function jsonStringToDate(string) {
- var match;
- if (match = string.match(R_ISO8601_STR)) {
- var date = new Date(0),
- tzHour = 0,
- tzMin = 0,
- dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
- timeSetter = match[8] ? date.setUTCHours : date.setHours;
-
- if (match[9]) {
- tzHour = int(match[9] + match[10]);
- tzMin = int(match[9] + match[11]);
- }
- dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
- var h = int(match[4]||0) - tzHour;
- var m = int(match[5]||0) - tzMin;
- var s = int(match[6]||0);
- var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
- timeSetter.call(date, h, m, s, ms);
- return date;
- }
- return string;
- }
-
-
- return function(date, format) {
- var text = '',
- parts = [],
- fn, match;
-
- format = format || 'mediumDate';
- format = $locale.DATETIME_FORMATS[format] || format;
- if (isString(date)) {
- if (NUMBER_STRING.test(date)) {
- date = int(date);
- } else {
- date = jsonStringToDate(date);
- }
- }
-
- if (isNumber(date)) {
- date = new Date(date);
- }
-
- if (!isDate(date)) {
- return date;
- }
-
- while(format) {
- match = DATE_FORMATS_SPLIT.exec(format);
- if (match) {
- parts = concat(parts, match, 1);
- format = parts.pop();
- } else {
- parts.push(format);
- format = null;
- }
- }
-
- forEach(parts, function(value){
- fn = DATE_FORMATS[value];
- text += fn ? fn(date, $locale.DATETIME_FORMATS)
- : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
- });
-
- return text;
- };
-}
-
-
-/**
- * @ngdoc filter
- * @name ng.filter:json
- * @function
- *
- * @description
- * Allows you to convert a JavaScript object into JSON string.
- *
- * This filter is mostly useful for debugging. When using the double curly {{value}} notation
- * the binding is automatically converted to JSON.
- *
- * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
- * @returns {string} JSON string.
- *
- *
- * @example:
-
-
-
{{ {'name':'value'} | json }}
-
-
- it('should jsonify filtered objects', function() {
- expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
- });
-
-
- *
- */
-function jsonFilter() {
- return function(object) {
- return toJson(object, true);
- };
-}
-
-
-/**
- * @ngdoc filter
- * @name ng.filter:lowercase
- * @function
- * @description
- * Converts string to lowercase.
- * @see angular.lowercase
- */
-var lowercaseFilter = valueFn(lowercase);
-
-
-/**
- * @ngdoc filter
- * @name ng.filter:uppercase
- * @function
- * @description
- * Converts string to uppercase.
- * @see angular.uppercase
- */
-var uppercaseFilter = valueFn(uppercase);
-
-/**
- * @ngdoc function
- * @name ng.filter:limitTo
- * @function
- *
- * @description
- * Creates a new array or string containing only a specified number of elements. The elements
- * are taken from either the beginning or the end of the source array or string, as specified by
- * the value and sign (positive or negative) of `limit`.
- *
- * @param {Array|string} input Source array or string to be limited.
- * @param {string|number} limit The length of the returned array or string. If the `limit` number
- * is positive, `limit` number of items from the beginning of the source array/string are copied.
- * If the number is negative, `limit` number of items from the end of the source array/string
- * are copied. The `limit` will be trimmed if it exceeds `array.length`
- * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
- * had less than `limit` elements.
- *
- * @example
-
-
-
-
-
-
- it('should limit the number array to first three items', function() {
- expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3');
- expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3');
- expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]');
- expect(binding('letters | limitTo:letterLimit')).toEqual('abc');
- });
-
- it('should update the output when -3 is entered', function() {
- input('numLimit').enter(-3);
- input('letterLimit').enter(-3);
- expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]');
- expect(binding('letters | limitTo:letterLimit')).toEqual('ghi');
- });
-
- it('should not exceed the maximum size of input array', function() {
- input('numLimit').enter(100);
- input('letterLimit').enter(100);
- expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]');
- expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi');
- });
-
-
- */
-function limitToFilter(){
- return function(input, limit) {
- if (!isArray(input) && !isString(input)) return input;
-
- limit = int(limit);
-
- if (isString(input)) {
- //NaN check on limit
- if (limit) {
- return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
- } else {
- return "";
- }
- }
-
- var out = [],
- i, n;
-
- // if abs(limit) exceeds maximum length, trim it
- if (limit > input.length)
- limit = input.length;
- else if (limit < -input.length)
- limit = -input.length;
-
- if (limit > 0) {
- i = 0;
- n = limit;
- } else {
- i = input.length + limit;
- n = input.length;
- }
-
- for (; i} expression A predicate to be
- * used by the comparator to determine the order of elements.
- *
- * Can be one of:
- *
- * - `function`: Getter function. The result of this function will be sorted using the
- * `<`, `=`, `>` operator.
- * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
- * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
- * ascending or descending sort order (for example, +name or -name).
- * - `Array`: An array of function or string predicates. The first predicate in the array
- * is used for sorting, but when two items are equivalent, the next predicate is used.
- *
- * @param {boolean=} reverse Reverse the order the array.
- * @returns {Array} Sorted copy of the source array.
- *
- * @example
-
-
-
-
-
-
- it('should be reverse ordered by aged', function() {
- expect(binding('predicate')).toBe('-age');
- expect(repeater('table.friend', 'friend in friends').column('friend.age')).
- toEqual(['35', '29', '21', '19', '10']);
- expect(repeater('table.friend', 'friend in friends').column('friend.name')).
- toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
- });
-
- it('should reorder the table when user selects different predicate', function() {
- element('.doc-example-live a:contains("Name")').click();
- expect(repeater('table.friend', 'friend in friends').column('friend.name')).
- toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
- expect(repeater('table.friend', 'friend in friends').column('friend.age')).
- toEqual(['35', '10', '29', '19', '21']);
-
- element('.doc-example-live a:contains("Phone")').click();
- expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
- toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
- expect(repeater('table.friend', 'friend in friends').column('friend.name')).
- toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
- });
-
-
- */
-orderByFilter.$inject = ['$parse'];
-function orderByFilter($parse){
- return function(array, sortPredicate, reverseOrder) {
- if (!isArray(array)) return array;
- if (!sortPredicate) return array;
- sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
- sortPredicate = map(sortPredicate, function(predicate){
- var descending = false, get = predicate || identity;
- if (isString(predicate)) {
- if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
- descending = predicate.charAt(0) == '-';
- predicate = predicate.substring(1);
- }
- get = $parse(predicate);
- }
- return reverseComparator(function(a,b){
- return compare(get(a),get(b));
- }, descending);
- });
- var arrayCopy = [];
- for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
- return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
-
- function comparator(o1, o2){
- for ( var i = 0; i < sortPredicate.length; i++) {
- var comp = sortPredicate[i](o1, o2);
- if (comp !== 0) return comp;
- }
- return 0;
- }
- function reverseComparator(comp, descending) {
- return toBoolean(descending)
- ? function(a,b){return comp(b,a);}
- : comp;
- }
- function compare(v1, v2){
- var t1 = typeof v1;
- var t2 = typeof v2;
- if (t1 == t2) {
- if (t1 == "string") {
- v1 = v1.toLowerCase();
- v2 = v2.toLowerCase();
- }
- if (v1 === v2) return 0;
- return v1 < v2 ? -1 : 1;
- } else {
- return t1 < t2 ? -1 : 1;
- }
- }
- };
-}
-
-function ngDirective(directive) {
- if (isFunction(directive)) {
- directive = {
- link: directive
- };
- }
- directive.restrict = directive.restrict || 'AC';
- return valueFn(directive);
-}
-
-/**
- * @ngdoc directive
- * @name ng.directive:a
- * @restrict E
- *
- * @description
- * Modifies the default behavior of the html A tag so that the default action is prevented when
- * the href attribute is empty.
- *
- * This change permits the easy creation of action links with the `ngClick` directive
- * without changing the location or causing page reloads, e.g.:
- * `Add Item`
- */
-var htmlAnchorDirective = valueFn({
- restrict: 'E',
- compile: function(element, attr) {
-
- if (msie <= 8) {
-
- // turn link into a stylable link in IE
- // but only if it doesn't have name attribute, in which case it's an anchor
- if (!attr.href && !attr.name) {
- attr.$set('href', '');
- }
-
- // add a comment node to anchors to workaround IE bug that causes element content to be reset
- // to new attribute content if attribute is updated with value containing @ and element also
- // contains value with @
- // see issue #1949
- element.append(document.createComment('IE fix'));
- }
-
- if (!attr.href && !attr.name) {
- return function(scope, element) {
- element.on('click', function(event){
- // if we have no href url, then don't navigate anywhere.
- if (!element.attr('href')) {
- event.preventDefault();
- }
- });
- };
- }
- }
-});
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngHref
- * @restrict A
- * @priority 99
- *
- * @description
- * Using Angular markup like `{{hash}}` in an href attribute will
- * make the link go to the wrong URL if the user clicks it before
- * Angular has a chance to replace the `{{hash}}` markup with its
- * value. Until Angular replaces the markup the link will be broken
- * and will most likely return a 404 error.
- *
- * The `ngHref` directive solves this problem.
- *
- * The wrong way to write it:
- *
- *
- *
- *
- * The correct way to write it:
- *
- *
- *
- *
- * @element A
- * @param {template} ngHref any string which can contain `{{}}` markup.
- *
- * @example
- * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
- * in links and their different behaviors:
-
-
-
- link 1 (link, don't reload)
- link 2 (link, don't reload)
- link 3 (link, reload!)
- anchor (link, don't reload)
- anchor (no link)
- link (link, change location)
-
-
- it('should execute ng-click but not reload when href without value', function() {
- element('#link-1').click();
- expect(input('value').val()).toEqual('1');
- expect(element('#link-1').attr('href')).toBe("");
- });
-
- it('should execute ng-click but not reload when href empty string', function() {
- element('#link-2').click();
- expect(input('value').val()).toEqual('2');
- expect(element('#link-2').attr('href')).toBe("");
- });
-
- it('should execute ng-click and change url when ng-href specified', function() {
- expect(element('#link-3').attr('href')).toBe("/123");
-
- element('#link-3').click();
- expect(browser().window().path()).toEqual('/123');
- });
-
- it('should execute ng-click but not reload when href empty string and name specified', function() {
- element('#link-4').click();
- expect(input('value').val()).toEqual('4');
- expect(element('#link-4').attr('href')).toBe('');
- });
-
- it('should execute ng-click but not reload when no href but name specified', function() {
- element('#link-5').click();
- expect(input('value').val()).toEqual('5');
- expect(element('#link-5').attr('href')).toBe(undefined);
- });
-
- it('should only change url when only ng-href', function() {
- input('value').enter('6');
- expect(element('#link-6').attr('href')).toBe('6');
-
- element('#link-6').click();
- expect(browser().location().url()).toEqual('/6');
- });
-
-
- */
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngSrc
- * @restrict A
- * @priority 99
- *
- * @description
- * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
- * work right: The browser will fetch from the URL with the literal
- * text `{{hash}}` until Angular replaces the expression inside
- * `{{hash}}`. The `ngSrc` directive solves this problem.
- *
- * The buggy way to write it:
- *
- *
- *
- *
- * The correct way to write it:
- *
- *
- *
- *
- * @element IMG
- * @param {template} ngSrc any string which can contain `{{}}` markup.
- */
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngSrcset
- * @restrict A
- * @priority 99
- *
- * @description
- * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
- * work right: The browser will fetch from the URL with the literal
- * text `{{hash}}` until Angular replaces the expression inside
- * `{{hash}}`. The `ngSrcset` directive solves this problem.
- *
- * The buggy way to write it:
- *
- *
- *
- *
- * The correct way to write it:
- *
- *
- *
- *
- * @element IMG
- * @param {template} ngSrcset any string which can contain `{{}}` markup.
- */
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngDisabled
- * @restrict A
- * @priority 100
- *
- * @description
- *
- * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
- *
- *
- *
- *
- *
- *
- * The HTML specification does not require browsers to preserve the values of boolean attributes
- * such as disabled. (Their presence means true and their absence means false.)
- * If we put an Angular interpolation expression into such an attribute then the
- * binding information would be lost when the browser removes the attribute.
- * The `ngDisabled` directive solves this problem for the `disabled` attribute.
- * This complementary directive is not removed by the browser and so provides
- * a permanent reliable place to store the binding information.
- *
- * @example
-
-
- Click me to toggle:
-
-
-
- it('should toggle button', function() {
- expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
- input('checked').check();
- expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
- });
-
-
- *
- * @element INPUT
- * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
- * then special attribute "disabled" will be set on the element
- */
-
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngChecked
- * @restrict A
- * @priority 100
- *
- * @description
- * The HTML specification does not require browsers to preserve the values of boolean attributes
- * such as checked. (Their presence means true and their absence means false.)
- * If we put an Angular interpolation expression into such an attribute then the
- * binding information would be lost when the browser removes the attribute.
- * The `ngChecked` directive solves this problem for the `checked` attribute.
- * This complementary directive is not removed by the browser and so provides
- * a permanent reliable place to store the binding information.
- * @example
-
-
- Check me to check both:
-
-
-
- it('should check both checkBoxes', function() {
- expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
- input('master').check();
- expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
- });
-
-
- *
- * @element INPUT
- * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
- * then special attribute "checked" will be set on the element
- */
-
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngReadonly
- * @restrict A
- * @priority 100
- *
- * @description
- * The HTML specification does not require browsers to preserve the values of boolean attributes
- * such as readonly. (Their presence means true and their absence means false.)
- * If we put an Angular interpolation expression into such an attribute then the
- * binding information would be lost when the browser removes the attribute.
- * The `ngReadonly` directive solves this problem for the `readonly` attribute.
- * This complementary directive is not removed by the browser and so provides
- * a permanent reliable place to store the binding information.
- * @example
-
-
- Check me to make text readonly:
-
-
-
- it('should toggle readonly attr', function() {
- expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
- input('checked').check();
- expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
- });
-
-
- *
- * @element INPUT
- * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
- * then special attribute "readonly" will be set on the element
- */
-
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngSelected
- * @restrict A
- * @priority 100
- *
- * @description
- * The HTML specification does not require browsers to preserve the values of boolean attributes
- * such as selected. (Their presence means true and their absence means false.)
- * If we put an Angular interpolation expression into such an attribute then the
- * binding information would be lost when the browser removes the attribute.
- * The `ngSelected` directive solves this problem for the `selected` atttribute.
- * This complementary directive is not removed by the browser and so provides
- * a permanent reliable place to store the binding information.
- *
- * @example
-
-
- Check me to select:
-
-
-
- it('should select Greetings!', function() {
- expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
- input('selected').check();
- expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
- });
-
-
- *
- * @element OPTION
- * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
- * then special attribute "selected" will be set on the element
- */
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngOpen
- * @restrict A
- * @priority 100
- *
- * @description
- * The HTML specification does not require browsers to preserve the values of boolean attributes
- * such as open. (Their presence means true and their absence means false.)
- * If we put an Angular interpolation expression into such an attribute then the
- * binding information would be lost when the browser removes the attribute.
- * The `ngOpen` directive solves this problem for the `open` attribute.
- * This complementary directive is not removed by the browser and so provides
- * a permanent reliable place to store the binding information.
- * @example
-
-
- Check me check multiple:
-
- Show/Hide me
-
-
-
- it('should toggle open', function() {
- expect(element('#details').prop('open')).toBeFalsy();
- input('open').check();
- expect(element('#details').prop('open')).toBeTruthy();
- });
-
-
- *
- * @element DETAILS
- * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
- * then special attribute "open" will be set on the element
- */
-
-var ngAttributeAliasDirectives = {};
-
-
-// boolean attrs are evaluated
-forEach(BOOLEAN_ATTR, function(propName, attrName) {
- // binding to multiple is not supported
- if (propName == "multiple") return;
-
- var normalized = directiveNormalize('ng-' + attrName);
- ngAttributeAliasDirectives[normalized] = function() {
- return {
- priority: 100,
- link: function(scope, element, attr) {
- scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
- attr.$set(attrName, !!value);
- });
- }
- };
- };
-});
-
-
-// ng-src, ng-srcset, ng-href are interpolated
-forEach(['src', 'srcset', 'href'], function(attrName) {
- var normalized = directiveNormalize('ng-' + attrName);
- ngAttributeAliasDirectives[normalized] = function() {
- return {
- priority: 99, // it needs to run after the attributes are interpolated
- link: function(scope, element, attr) {
- attr.$observe(normalized, function(value) {
- if (!value)
- return;
-
- attr.$set(attrName, value);
-
- // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
- // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
- // to set the property as well to achieve the desired effect.
- // we use attr[attrName] value since $set can sanitize the url.
- if (msie) element.prop(attrName, attr[attrName]);
- });
- }
- };
- };
-});
-
-/* global -nullFormCtrl */
-var nullFormCtrl = {
- $addControl: noop,
- $removeControl: noop,
- $setValidity: noop,
- $setDirty: noop,
- $setPristine: noop
-};
-
-/**
- * @ngdoc object
- * @name ng.directive:form.FormController
- *
- * @property {boolean} $pristine True if user has not interacted with the form yet.
- * @property {boolean} $dirty True if user has already interacted with the form.
- * @property {boolean} $valid True if all of the containing forms and controls are valid.
- * @property {boolean} $invalid True if at least one containing control or form is invalid.
- *
- * @property {Object} $error Is an object hash, containing references to all invalid controls or
- * forms, where:
- *
- * - keys are validation tokens (error names),
- * - values are arrays of controls or forms that are invalid for given error name.
- *
- *
- * Built-in validation tokens:
- *
- * - `email`
- * - `max`
- * - `maxlength`
- * - `min`
- * - `minlength`
- * - `number`
- * - `pattern`
- * - `required`
- * - `url`
- *
- * @description
- * `FormController` keeps track of all its controls and nested forms as well as state of them,
- * such as being valid/invalid or dirty/pristine.
- *
- * Each {@link ng.directive:form form} directive creates an instance
- * of `FormController`.
- *
- */
-//asks for $scope to fool the BC controller module
-FormController.$inject = ['$element', '$attrs', '$scope'];
-function FormController(element, attrs) {
- var form = this,
- parentForm = element.parent().controller('form') || nullFormCtrl,
- invalidCount = 0, // used to easily determine if we are valid
- errors = form.$error = {},
- controls = [];
-
- // init state
- form.$name = attrs.name || attrs.ngForm;
- form.$dirty = false;
- form.$pristine = true;
- form.$valid = true;
- form.$invalid = false;
-
- parentForm.$addControl(form);
-
- // Setup initial state of the control
- element.addClass(PRISTINE_CLASS);
- toggleValidCss(true);
-
- // convenience method for easy toggling of classes
- function toggleValidCss(isValid, validationErrorKey) {
- validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
- element.
- removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
- addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
- }
-
- /**
- * @ngdoc function
- * @name ng.directive:form.FormController#$addControl
- * @methodOf ng.directive:form.FormController
- *
- * @description
- * Register a control with the form.
- *
- * Input elements using ngModelController do this automatically when they are linked.
- */
- form.$addControl = function(control) {
- // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
- // and not added to the scope. Now we throw an error.
- assertNotHasOwnProperty(control.$name, 'input');
- controls.push(control);
-
- if (control.$name) {
- form[control.$name] = control;
- }
- };
-
- /**
- * @ngdoc function
- * @name ng.directive:form.FormController#$removeControl
- * @methodOf ng.directive:form.FormController
- *
- * @description
- * Deregister a control from the form.
- *
- * Input elements using ngModelController do this automatically when they are destroyed.
- */
- form.$removeControl = function(control) {
- if (control.$name && form[control.$name] === control) {
- delete form[control.$name];
- }
- forEach(errors, function(queue, validationToken) {
- form.$setValidity(validationToken, true, control);
- });
-
- arrayRemove(controls, control);
- };
-
- /**
- * @ngdoc function
- * @name ng.directive:form.FormController#$setValidity
- * @methodOf ng.directive:form.FormController
- *
- * @description
- * Sets the validity of a form control.
- *
- * This method will also propagate to parent forms.
- */
- form.$setValidity = function(validationToken, isValid, control) {
- var queue = errors[validationToken];
-
- if (isValid) {
- if (queue) {
- arrayRemove(queue, control);
- if (!queue.length) {
- invalidCount--;
- if (!invalidCount) {
- toggleValidCss(isValid);
- form.$valid = true;
- form.$invalid = false;
- }
- errors[validationToken] = false;
- toggleValidCss(true, validationToken);
- parentForm.$setValidity(validationToken, true, form);
- }
- }
-
- } else {
- if (!invalidCount) {
- toggleValidCss(isValid);
- }
- if (queue) {
- if (includes(queue, control)) return;
- } else {
- errors[validationToken] = queue = [];
- invalidCount++;
- toggleValidCss(false, validationToken);
- parentForm.$setValidity(validationToken, false, form);
- }
- queue.push(control);
-
- form.$valid = false;
- form.$invalid = true;
- }
- };
-
- /**
- * @ngdoc function
- * @name ng.directive:form.FormController#$setDirty
- * @methodOf ng.directive:form.FormController
- *
- * @description
- * Sets the form to a dirty state.
- *
- * This method can be called to add the 'ng-dirty' class and set the form to a dirty
- * state (ng-dirty class). This method will also propagate to parent forms.
- */
- form.$setDirty = function() {
- element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
- form.$dirty = true;
- form.$pristine = false;
- parentForm.$setDirty();
- };
-
- /**
- * @ngdoc function
- * @name ng.directive:form.FormController#$setPristine
- * @methodOf ng.directive:form.FormController
- *
- * @description
- * Sets the form to its pristine state.
- *
- * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
- * state (ng-pristine class). This method will also propagate to all the controls contained
- * in this form.
- *
- * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
- * saving or resetting it.
- */
- form.$setPristine = function () {
- element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
- form.$dirty = false;
- form.$pristine = true;
- forEach(controls, function(control) {
- control.$setPristine();
- });
- };
-}
-
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngForm
- * @restrict EAC
- *
- * @description
- * Nestable alias of {@link ng.directive:form `form`} directive. HTML
- * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
- * sub-group of controls needs to be determined.
- *
- * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
- * related scope, under this name.
- *
- */
-
- /**
- * @ngdoc directive
- * @name ng.directive:form
- * @restrict E
- *
- * @description
- * Directive that instantiates
- * {@link ng.directive:form.FormController FormController}.
- *
- * If the `name` attribute is specified, the form controller is published onto the current scope under
- * this name.
- *
- * # Alias: {@link ng.directive:ngForm `ngForm`}
- *
- * In Angular forms can be nested. This means that the outer form is valid when all of the child
- * forms are valid as well. However, browsers do not allow nesting of `
-
+
it('should load and compile correct template', function() {
- element('a:contains("Moby: Ch1")').click();
- var content = element('.doc-example-live [ng-view]').text();
+ element(by.linkText('Moby: Ch1')).click();
+ var content = element(by.css('.doc-example-live [ng-view]')).getText();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
- element('a:contains("Scarlet")').click();
- sleep(2); // promises are not part of scenario waiting
- content = element('.doc-example-live [ng-view]').text();
+ element(by.partialLinkText('Scarlet')).click();
+
+ content = element(by.css('.doc-example-live [ng-view]')).getText();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
@@ -375,7 +375,7 @@ function $RouteProvider(){
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
- * resolving all of the dependencies needed for the route change to occurs.
+ * resolving all of the dependencies needed for the route change to occur.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
@@ -794,16 +794,17 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory);
}
-
+
it('should load and compile correct template', function() {
- element('a:contains("Moby: Ch1")').click();
- var content = element('.doc-example-live [ng-view]').text();
+ element(by.linkText('Moby: Ch1')).click();
+ var content = element(by.css('.doc-example-live [ng-view]')).getText();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
- element('a:contains("Scarlet")').click();
- content = element('.doc-example-live [ng-view]').text();
+ element(by.partialLinkText('Scarlet')).click();
+
+ content = element(by.css('.doc-example-live [ng-view]')).getText();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
diff --git a/awx/ui/static/lib/angular-route/angular-route.min.js b/awx/ui/static/lib/angular-route/angular-route.min.js
new file mode 100644
index 0000000000..fe8e00cc5e
--- /dev/null
+++ b/awx/ui/static/lib/angular-route/angular-route.min.js
@@ -0,0 +1,14 @@
+/*
+ AngularJS v1.2.12
+ (c) 2010-2014 Google, Inc. http://angularjs.org
+ License: MIT
+*/
+(function(h,e,A){'use strict';function u(w,q,k){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,c,b,f,n){function y(){l&&(l.$destroy(),l=null);g&&(k.leave(g),g=null)}function v(){var b=w.current&&w.current.locals;if(e.isDefined(b&&b.$template)){var b=a.$new(),f=w.current;g=n(b,function(d){k.enter(d,null,g||c,function(){!e.isDefined(t)||t&&!a.$eval(t)||q()});y()});l=f.scope=b;l.$emit("$viewContentLoaded");l.$eval(h)}else y()}var l,g,t=b.autoscroll,h=b.onload||"";
+a.$on("$routeChangeSuccess",v);v()}}}function z(e,h,k){return{restrict:"ECA",priority:-400,link:function(a,c){var b=k.current,f=b.locals;c.html(f.$template);var n=e(c.contents());b.controller&&(f.$scope=a,f=h(b.controller,f),b.controllerAs&&(a[b.controllerAs]=f),c.data("$ngControllerController",f),c.children().data("$ngControllerController",f));n(a)}}}h=e.module("ngRoute",["ng"]).provider("$route",function(){function h(a,c){return e.extend(new (e.extend(function(){},{prototype:a})),c)}function q(a,
+e){var b=e.caseInsensitiveMatch,f={originalPath:a,regexp:a},h=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?\*])?/g,function(a,e,b,c){a="?"===c?c:null;c="*"===c?c:null;h.push({name:b,optional:!!a});e=e||"";return""+(a?"":e)+"(?:"+(a?e:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=RegExp("^"+a+"$",b?"i":"");return f}var k={};this.when=function(a,c){k[a]=e.extend({reloadOnSearch:!0},c,a&&q(a,c));if(a){var b="/"==a[a.length-1]?a.substr(0,a.length-
+1):a+"/";k[b]=e.extend({redirectTo:a},q(b,c))}return this};this.otherwise=function(a){this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$http","$templateCache","$sce",function(a,c,b,f,n,q,v,l){function g(){var d=t(),m=r.current;if(d&&m&&d.$$route===m.$$route&&e.equals(d.pathParams,m.pathParams)&&!d.reloadOnSearch&&!x)m.params=d.params,e.copy(m.params,b),a.$broadcast("$routeUpdate",m);else if(d||m)x=!1,a.$broadcast("$routeChangeStart",d,m),(r.current=
+d)&&d.redirectTo&&(e.isString(d.redirectTo)?c.path(u(d.redirectTo,d.params)).search(d.params).replace():c.url(d.redirectTo(d.pathParams,c.path(),c.search())).replace()),f.when(d).then(function(){if(d){var a=e.extend({},d.resolve),c,b;e.forEach(a,function(d,c){a[c]=e.isString(d)?n.get(d):n.invoke(d)});e.isDefined(c=d.template)?e.isFunction(c)&&(c=c(d.params)):e.isDefined(b=d.templateUrl)&&(e.isFunction(b)&&(b=b(d.params)),b=l.getTrustedResourceUrl(b),e.isDefined(b)&&(d.loadedTemplateUrl=b,c=q.get(b,
+{cache:v}).then(function(a){return a.data})));e.isDefined(c)&&(a.$template=c);return f.all(a)}}).then(function(c){d==r.current&&(d&&(d.locals=c,e.copy(d.params,b)),a.$broadcast("$routeChangeSuccess",d,m))},function(c){d==r.current&&a.$broadcast("$routeChangeError",d,m,c)})}function t(){var a,b;e.forEach(k,function(f,k){var p;if(p=!b){var s=c.path();p=f.keys;var l={};if(f.regexp)if(s=f.regexp.exec(s)){for(var g=1,q=s.length;g` to your `index.html`:
+
+```html
+
+```
+
+And add `ngSanitize` as a dependency for your app:
+
+```javascript
+angular.module('myApp', ['ngSanitize']);
+```
+
+## Documentation
+
+Documentation is available on the
+[AngularJS docs site](http://docs.angularjs.org/api/ngSanitize).
+
+## License
+
+The MIT License
+
+Copyright (c) 2010-2012 Google, Inc. http://angularjs.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/awx/ui/static/lib/angular-1.2.9/angular-sanitize.js b/awx/ui/static/lib/angular-sanitize/angular-sanitize.js
similarity index 89%
rename from awx/ui/static/lib/angular-1.2.9/angular-sanitize.js
rename to awx/ui/static/lib/angular-sanitize/angular-sanitize.js
index 8d7af2bea8..f773766a5d 100644
--- a/awx/ui/static/lib/angular-1.2.9/angular-sanitize.js
+++ b/awx/ui/static/lib/angular-sanitize/angular-sanitize.js
@@ -1,5 +1,5 @@
/**
- * @license AngularJS v1.2.9
+ * @license AngularJS v1.2.12
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
@@ -104,35 +104,37 @@ var $sanitizeMinErr = angular.$$minErr('$sanitize');
-
+
it('should sanitize the html snippet by default', function() {
- expect(using('#bind-html-with-sanitize').element('div').html()).
+ expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('
an html\nclick here\nsnippet
');
});
it('should inline raw snippet if bound to a trusted value', function() {
- expect(using('#bind-html-with-trust').element("div").html()).
+ expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
toBe("
an html\n" +
"click here\n" +
"snippet
");
});
it('should escape snippet without any filter', function() {
- expect(using('#bind-default').element('div').html()).
+ expect(element(by.css('#bind-default div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
- input('snippet').enter('new text');
- expect(using('#bind-html-with-sanitize').element('div').html()).toBe('new text');
- expect(using('#bind-html-with-trust').element('div').html()).toBe(
+ element(by.model('snippet')).clear();
+ element(by.model('snippet')).sendKeys('new text');
+ expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
+ toBe('new text');
+ expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
'new text');
- expect(using('#bind-default').element('div').html()).toBe(
+ expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
"new <b onclick=\"alert(1)\">text</b>");
});
-
+
*/
function $SanitizeProvider() {
@@ -537,37 +539,38 @@ angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
-
+
it('should linkify the snippet with urls', function() {
- expect(using('#linky-filter').binding('snippet | linky')).
- toBe('Pretty text with some links:
' +
- 'http://angularjs.org/,
' +
- 'us@somewhere.org,
' +
- 'another@somewhere.org,
' +
- 'and one more: ftp://127.0.0.1/.');
+ expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
+ toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
+ 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
+ expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
});
- it ('should not linkify snippet without the linky filter', function() {
- expect(using('#escaped-html').binding('snippet')).
- toBe("Pretty text with some links:\n" +
- "http://angularjs.org/,\n" +
- "mailto:us@somewhere.org,\n" +
- "another@somewhere.org,\n" +
- "and one more: ftp://127.0.0.1/.");
+ it('should not linkify snippet without the linky filter', function() {
+ expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
+ toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
+ 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
+ expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
});
it('should update', function() {
- input('snippet').enter('new http://link.');
- expect(using('#linky-filter').binding('snippet | linky')).
- toBe('new http://link.');
- expect(using('#escaped-html').binding('snippet')).toBe('new http://link.');
+ element(by.model('snippet')).clear();
+ element(by.model('snippet')).sendKeys('new http://link.');
+ expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
+ toBe('new http://link.');
+ expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
+ expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
+ .toBe('new http://link.');
});
it('should work with the target property', function() {
- expect(using('#linky-target').binding("snippetWithTarget | linky:'_blank'")).
- toBe('http://angularjs.org/');
+ expect(element(by.id('linky-target')).
+ element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
+ toBe('http://angularjs.org/');
+ expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
});
-
+
*/
angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
diff --git a/awx/ui/static/lib/angular-1.2.9/angular-sanitize.min.js b/awx/ui/static/lib/angular-sanitize/angular-sanitize.min.js
similarity index 99%
rename from awx/ui/static/lib/angular-1.2.9/angular-sanitize.min.js
rename to awx/ui/static/lib/angular-sanitize/angular-sanitize.min.js
index 3825980233..24d99afeaf 100644
--- a/awx/ui/static/lib/angular-1.2.9/angular-sanitize.min.js
+++ b/awx/ui/static/lib/angular-sanitize/angular-sanitize.min.js
@@ -1,5 +1,5 @@
/*
- AngularJS v1.2.9
+ AngularJS v1.2.12
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
diff --git a/awx/ui/static/lib/angular-1.2.9/angular-sanitize.min.js.map b/awx/ui/static/lib/angular-sanitize/angular-sanitize.min.js.map
similarity index 94%
rename from awx/ui/static/lib/angular-1.2.9/angular-sanitize.min.js.map
rename to awx/ui/static/lib/angular-sanitize/angular-sanitize.min.js.map
index 30ec404993..c479150a70 100644
--- a/awx/ui/static/lib/angular-1.2.9/angular-sanitize.min.js.map
+++ b/awx/ui/static/lib/angular-sanitize/angular-sanitize.min.js.map
@@ -2,7 +2,7 @@
"version":3,
"file":"angular-sanitize.min.js",
"lineCount":13,
-"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAgJtCC,QAASA,EAAY,CAACC,CAAD,CAAQ,CAC3B,IAAIC,EAAM,EACGC,EAAAC,CAAmBF,CAAnBE,CAAwBN,CAAAO,KAAxBD,CACbH,MAAA,CAAaA,CAAb,CACA,OAAOC,EAAAI,KAAA,CAAS,EAAT,CAJoB,CAmE7BC,QAASA,EAAO,CAACC,CAAD,CAAM,CAAA,IAChBC,EAAM,EAAIC,EAAAA,CAAQF,CAAAG,MAAA,CAAU,GAAV,CAAtB,KAAsCC,CACtC,KAAKA,CAAL,CAAS,CAAT,CAAYA,CAAZ,CAAgBF,CAAAG,OAAhB,CAA8BD,CAAA,EAA9B,CAAmCH,CAAA,CAAIC,CAAA,CAAME,CAAN,CAAJ,CAAA,CAAgB,CAAA,CACnD,OAAOH,EAHa,CAmBtBK,QAASA,EAAU,CAAEC,CAAF,CAAQC,CAAR,CAAkB,CAiFnCC,QAASA,EAAa,CAAEC,CAAF,CAAOC,CAAP,CAAgBC,CAAhB,CAAsBC,CAAtB,CAA8B,CAClDF,CAAA,CAAUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,IAAKI,CAAA,CAAeJ,CAAf,CAAL,CACE,IAAA,CAAQK,CAAAC,KAAA,EAAR,EAAwBC,CAAA,CAAgBF,CAAAC,KAAA,EAAhB,CAAxB,CAAA,CACEE,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CAICG,EAAA,CAAwBT,CAAxB,CAAL,EAA0CK,CAAAC,KAAA,EAA1C,EAA0DN,CAA1D,EACEQ,CAAA,CAAa,EAAb,CAAiBR,CAAjB,CAKF,EAFAE,CAEA,CAFQQ,CAAA,CAAcV,CAAd,CAER,EAFmC,CAAC,CAACE,CAErC,GACEG,CAAAM,KAAA,CAAYX,CAAZ,CAEF,KAAIY,EAAQ,EAEZX,EAAAY,QAAA,CAAaC,CAAb,CACE,QAAQ,CAACC,CAAD,CAAQC,CAAR,CAAcC,CAAd,CAAiCC,CAAjC,CAAoDC,CAApD,CAAmE,CAMzEP,CAAA,CAAMI,CAAN,CAAA,CAAcI,CAAA,CALFH,CAKE,EAJTC,CAIS,EAHTC,CAGS,EAFT,EAES,CAN2D,CAD7E,CASItB,EAAAwB,MAAJ,EAAmBxB,CAAAwB,MAAA,CAAerB,CAAf,CAAwBY,CAAxB,CAA+BV,CAA/B,CA5B+B,CA+BpDM,QAASA,EAAW,CAAET,CAAF,CAAOC,CAAP,CAAiB,CAAA,IAC/BsB,EAAM,CADyB,CACtB7B,CAEb,IADAO,CACA,CADUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,CAEE,IAAMsB,CAAN,CAAYjB,CAAAX,OAAZ,CAA2B,CAA3B,CAAqC,CAArC,EAA8B4B,CAA9B,EACOjB,CAAA,CAAOiB,CAAP,CADP,EACuBtB,CADvB,CAAwCsB,CAAA,EAAxC;AAIF,GAAY,CAAZ,EAAKA,CAAL,CAAgB,CAEd,IAAM7B,CAAN,CAAUY,CAAAX,OAAV,CAAyB,CAAzB,CAA4BD,CAA5B,EAAiC6B,CAAjC,CAAsC7B,CAAA,EAAtC,CACMI,CAAA0B,IAAJ,EAAiB1B,CAAA0B,IAAA,CAAalB,CAAA,CAAOZ,CAAP,CAAb,CAGnBY,EAAAX,OAAA,CAAe4B,CAND,CATmB,CAhHF,IAC/BE,CAD+B,CACxB1C,CADwB,CACVuB,EAAQ,EADE,CACEC,EAAOV,CAG5C,KAFAS,CAAAC,KAEA,CAFamB,QAAQ,EAAG,CAAE,MAAOpB,EAAA,CAAOA,CAAAX,OAAP,CAAsB,CAAtB,CAAT,CAExB,CAAQE,CAAR,CAAA,CAAe,CACbd,CAAA,CAAQ,CAAA,CAGR,IAAMuB,CAAAC,KAAA,EAAN,EAAuBoB,CAAA,CAAiBrB,CAAAC,KAAA,EAAjB,CAAvB,CAmDEV,CASA,CATOA,CAAAiB,QAAA,CAAiBc,MAAJ,CAAW,kBAAX,CAAgCtB,CAAAC,KAAA,EAAhC,CAA+C,QAA/C,CAAyD,GAAzD,CAAb,CACL,QAAQ,CAACsB,CAAD,CAAMC,CAAN,CAAW,CACjBA,CAAA,CAAOA,CAAAhB,QAAA,CAAaiB,CAAb,CAA6B,IAA7B,CAAAjB,QAAA,CAA2CkB,CAA3C,CAAyD,IAAzD,CAEHlC,EAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeS,CAAf,CAAf,CAEnB,OAAO,EALU,CADd,CASP,CAAArB,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CA5DF,KAAyD,CAGvD,GAA8B,CAA9B,GAAKV,CAAAoC,QAAA,CAAa,SAAb,CAAL,CAEER,CAEA,CAFQ5B,CAAAoC,QAAA,CAAa,IAAb,CAAmB,CAAnB,CAER,CAAc,CAAd,EAAKR,CAAL,EAAmB5B,CAAAqC,YAAA,CAAiB,QAAjB,CAAwBT,CAAxB,CAAnB,GAAsDA,CAAtD,GACM3B,CAAAqC,QAEJ,EAFqBrC,CAAAqC,QAAA,CAAiBtC,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAAjB,CAErB,CADA5B,CACA,CADOA,CAAAuC,UAAA,CAAgBX,CAAhB,CAAwB,CAAxB,CACP,CAAA1C,CAAA,CAAQ,CAAA,CAHV,CAJF,KAUO,IAAKsD,CAAAC,KAAA,CAAoBzC,CAApB,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYqB,CAAZ,CAER,CACExC,CACA;AADOA,CAAAiB,QAAA,CAAcE,CAAA,CAAM,CAAN,CAAd,CAAyB,EAAzB,CACP,CAAAjC,CAAA,CAAQ,CAAA,CAFV,CAHK,IAQA,IAAKwD,CAAAD,KAAA,CAA4BzC,CAA5B,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYwB,CAAZ,CAER,CACE3C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB0B,CAAlB,CAAkC/B,CAAlC,CACA,CAAA1B,CAAA,CAAQ,CAAA,CAHV,CAHK,IAUK0D,EAAAH,KAAA,CAAsBzC,CAAtB,CAAL,GACLmB,CADK,CACGnB,CAAAmB,MAAA,CAAY0B,CAAZ,CADH,IAIH7C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB4B,CAAlB,CAAoC3C,CAApC,CACA,CAAAhB,CAAA,CAAQ,CAAA,CANL,CAUFA,EAAL,GACE0C,CAKA,CALQ5B,CAAAoC,QAAA,CAAa,GAAb,CAKR,CAHIH,CAGJ,CAHmB,CAAR,CAAAL,CAAA,CAAY5B,CAAZ,CAAmBA,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAG9B,CAFA5B,CAEA,CAFe,CAAR,CAAA4B,CAAA,CAAY,EAAZ,CAAiB5B,CAAAuC,UAAA,CAAgBX,CAAhB,CAExB,CAAI3B,CAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeS,CAAf,CAAf,CANrB,CAzCuD,CA+DzD,GAAKjC,CAAL,EAAaU,CAAb,CACE,KAAMoC,EAAA,CAAgB,UAAhB,CAC4C9C,CAD5C,CAAN,CAGFU,CAAA,CAAOV,CAvEM,CA2EfY,CAAA,EA/EmC,CA2IrCY,QAASA,EAAc,CAACuB,CAAD,CAAQ,CAC7B,GAAI,CAACA,CAAL,CAAc,MAAO,EAIrB,KAAIC,EAAQC,CAAAC,KAAA,CAAaH,CAAb,CACRI,EAAAA,CAAcH,CAAA,CAAM,CAAN,CAClB,KAAII,EAAaJ,CAAA,CAAM,CAAN,CAEjB,IADIK,CACJ,CADcL,CAAA,CAAM,CAAN,CACd,CACEM,CAAAC,UAKA,CALoBF,CAAApC,QAAA,CAAgB,IAAhB,CAAqB,MAArB,CAKpB,CAAAoC,CAAA,CAAU,aAAA,EAAiBC,EAAjB,CACRA,CAAAE,YADQ,CACgBF,CAAAG,UAE5B,OAAON,EAAP,CAAqBE,CAArB,CAA+BD,CAlBF,CA4B/BM,QAASA,EAAc,CAACX,CAAD,CAAQ,CAC7B,MAAOA,EAAA9B,QAAA,CACG,IADH;AACS,OADT,CAAAA,QAAA,CAEG0C,CAFH,CAE4B,QAAQ,CAACZ,CAAD,CAAO,CAC9C,MAAO,IAAP,CAAcA,CAAAa,WAAA,CAAiB,CAAjB,CAAd,CAAoC,GADU,CAF3C,CAAA3C,QAAA,CAKG,IALH,CAKS,MALT,CAAAA,QAAA,CAMG,IANH,CAMS,MANT,CADsB,CAoB/B7B,QAASA,EAAkB,CAACD,CAAD,CAAM0E,CAAN,CAAmB,CAC5C,IAAIC,EAAS,CAAA,CAAb,CACIC,EAAMhF,CAAAiF,KAAA,CAAa7E,CAAb,CAAkBA,CAAA4B,KAAlB,CACV,OAAO,OACEU,QAAQ,CAACtB,CAAD,CAAMa,CAAN,CAAaV,CAAb,CAAmB,CAChCH,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD2D,EAAAA,CAAL,EAAehC,CAAA,CAAgB3B,CAAhB,CAAf,GACE2D,CADF,CACW3D,CADX,CAGK2D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAc9D,CAAd,CAAf,GACE4D,CAAA,CAAI,GAAJ,CAcA,CAbAA,CAAA,CAAI5D,CAAJ,CAaA,CAZApB,CAAAmF,QAAA,CAAgBlD,CAAhB,CAAuB,QAAQ,CAAC+B,CAAD,CAAQoB,CAAR,CAAY,CACzC,IAAIC,EAAKrF,CAAAwB,UAAA,CAAkB4D,CAAlB,CAAT,CACIE,EAAmB,KAAnBA,GAAWlE,CAAXkE,EAAqC,KAArCA,GAA4BD,CAA5BC,EAAyD,YAAzDA,GAAgDD,CAC3B,EAAA,CAAzB,GAAIE,CAAA,CAAWF,CAAX,CAAJ,EACsB,CAAA,CADtB,GACGG,CAAA,CAASH,CAAT,CADH,EAC8B,CAAAP,CAAA,CAAad,CAAb,CAAoBsB,CAApB,CAD9B,GAEEN,CAAA,CAAI,GAAJ,CAIA,CAHAA,CAAA,CAAII,CAAJ,CAGA,CAFAJ,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIL,CAAA,CAAeX,CAAf,CAAJ,CACA,CAAAgB,CAAA,CAAI,GAAJ,CANF,CAHyC,CAA3C,CAYA,CAAAA,CAAA,CAAIzD,CAAA,CAAQ,IAAR,CAAe,GAAnB,CAfF,CALgC,CAD7B,KAwBAqB,QAAQ,CAACxB,CAAD,CAAK,CACdA,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD2D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAc9D,CAAd,CAAf,GACE4D,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAI5D,CAAJ,CACA,CAAA4D,CAAA,CAAI,GAAJ,CAHF,CAKI5D,EAAJ,EAAW2D,CAAX,GACEA,CADF,CACW,CAAA,CADX,CAPc,CAxBb,OAmCE5E,QAAQ,CAACA,CAAD,CAAO,CACb4E,CAAL;AACEC,CAAA,CAAIL,CAAA,CAAexE,CAAf,CAAJ,CAFgB,CAnCjB,CAHqC,CA/Z9C,IAAI4D,EAAkB/D,CAAAyF,SAAA,CAAiB,WAAjB,CAAtB,CAuJI3B,EACG,4FAxJP,CAyJEF,EAAiB,2BAzJnB,CA0JEzB,EAAc,yEA1JhB,CA2JE0B,EAAmB,IA3JrB,CA4JEF,EAAyB,SA5J3B,CA6JER,EAAiB,qBA7JnB,CA8JEM,EAAiB,qBA9JnB,CA+JEL,EAAe,yBA/JjB,CAiKEwB,EAA0B,gBAjK5B,CA0KI7C,EAAetB,CAAA,CAAQ,wBAAR,CAIfiF,EAAAA,CAA8BjF,CAAA,CAAQ,gDAAR,CAC9BkF,EAAAA,CAA+BlF,CAAA,CAAQ,OAAR,CADnC,KAEIqB,EAAyB9B,CAAA4F,OAAA,CAAe,EAAf,CACeD,CADf,CAEeD,CAFf,CAF7B,CAOIjE,EAAgBzB,CAAA4F,OAAA,CAAe,EAAf,CAAmBF,CAAnB,CAAgDjF,CAAA,CAAQ,4KAAR,CAAhD,CAPpB;AAYImB,EAAiB5B,CAAA4F,OAAA,CAAe,EAAf,CAAmBD,CAAnB,CAAiDlF,CAAA,CAAQ,2JAAR,CAAjD,CAZrB,CAkBIsC,EAAkBtC,CAAA,CAAQ,cAAR,CAlBtB,CAoBIyE,EAAgBlF,CAAA4F,OAAA,CAAe,EAAf,CACe7D,CADf,CAEeN,CAFf,CAGeG,CAHf,CAIeE,CAJf,CApBpB,CA2BI0D,EAAW/E,CAAA,CAAQ,0CAAR,CA3Bf,CA4BI8E,EAAavF,CAAA4F,OAAA,CAAe,EAAf,CAAmBJ,CAAnB,CAA6B/E,CAAA,CAC1C,ySAD0C,CAA7B,CA5BjB;AA0LI8D,EAAUsB,QAAAC,cAAA,CAAuB,KAAvB,CA1Ld,CA2LI5B,EAAU,wBAsGdlE,EAAA+F,OAAA,CAAe,YAAf,CAA6B,EAA7B,CAAAC,SAAA,CAA0C,WAA1C,CA7UAC,QAA0B,EAAG,CAC3B,IAAAC,KAAA,CAAY,CAAC,eAAD,CAAkB,QAAQ,CAACC,CAAD,CAAgB,CACpD,MAAO,SAAQ,CAAClF,CAAD,CAAO,CACpB,IAAIb,EAAM,EACVY,EAAA,CAAWC,CAAX,CAAiBZ,CAAA,CAAmBD,CAAnB,CAAwB,QAAQ,CAACgG,CAAD,CAAMd,CAAN,CAAe,CAC9D,MAAO,CAAC,SAAA5B,KAAA,CAAeyC,CAAA,CAAcC,CAAd,CAAmBd,CAAnB,CAAf,CADsD,CAA/C,CAAjB,CAGA,OAAOlF,EAAAI,KAAA,CAAS,EAAT,CALa,CAD8B,CAA1C,CADe,CA6U7B,CAsGAR,EAAA+F,OAAA,CAAe,YAAf,CAAAM,OAAA,CAAoC,OAApC,CAA6C,CAAC,WAAD,CAAc,QAAQ,CAACC,CAAD,CAAY,CAAA,IACzEC,EACE,mEAFuE,CAGzEC,EAAgB,UAEpB,OAAO,SAAQ,CAACtD,CAAD,CAAOuD,CAAP,CAAe,CAoB5BC,QAASA,EAAO,CAACxD,CAAD,CAAO,CAChBA,CAAL,EAGAjC,CAAAe,KAAA,CAAU9B,CAAA,CAAagD,CAAb,CAAV,CAJqB,CAOvByD,QAASA,EAAO,CAACC,CAAD,CAAM1D,CAAN,CAAY,CAC1BjC,CAAAe,KAAA,CAAU,KAAV,CACIhC,EAAA6G,UAAA,CAAkBJ,CAAlB,CAAJ;CACExF,CAAAe,KAAA,CAAU,UAAV,CAEA,CADAf,CAAAe,KAAA,CAAUyE,CAAV,CACA,CAAAxF,CAAAe,KAAA,CAAU,IAAV,CAHF,CAKAf,EAAAe,KAAA,CAAU,QAAV,CACAf,EAAAe,KAAA,CAAU4E,CAAV,CACA3F,EAAAe,KAAA,CAAU,IAAV,CACA0E,EAAA,CAAQxD,CAAR,CACAjC,EAAAe,KAAA,CAAU,MAAV,CAX0B,CA1B5B,GAAI,CAACkB,CAAL,CAAW,MAAOA,EAMlB,KALA,IAAId,CAAJ,CACI0E,EAAM5D,CADV,CAEIjC,EAAO,EAFX,CAGI2F,CAHJ,CAII9F,CACJ,CAAQsB,CAAR,CAAgB0E,CAAA1E,MAAA,CAAUmE,CAAV,CAAhB,CAAA,CAEEK,CAMA,CANMxE,CAAA,CAAM,CAAN,CAMN,CAJIA,CAAA,CAAM,CAAN,CAIJ,EAJgBA,CAAA,CAAM,CAAN,CAIhB,GAJ0BwE,CAI1B,CAJgC,SAIhC,CAJ4CA,CAI5C,EAHA9F,CAGA,CAHIsB,CAAAS,MAGJ,CAFA6D,CAAA,CAAQI,CAAAC,OAAA,CAAW,CAAX,CAAcjG,CAAd,CAAR,CAEA,CADA6F,CAAA,CAAQC,CAAR,CAAaxE,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAiBsE,CAAjB,CAAgC,EAAhC,CAAb,CACA,CAAAM,CAAA,CAAMA,CAAAtD,UAAA,CAAc1C,CAAd,CAAkBsB,CAAA,CAAM,CAAN,CAAArB,OAAlB,CAER2F,EAAA,CAAQI,CAAR,CACA,OAAOR,EAAA,CAAUrF,CAAAT,KAAA,CAAU,EAAV,CAAV,CAlBqB,CAL+C,CAAlC,CAA7C,CAvjBsC,CAArC,CAAA,CAwmBET,MAxmBF,CAwmBUA,MAAAC,QAxmBV;",
+"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkBC,CAAlB,CAA6B,CAkJtCC,QAASA,EAAY,CAACC,CAAD,CAAQ,CAC3B,IAAIC,EAAM,EACGC,EAAAC,CAAmBF,CAAnBE,CAAwBN,CAAAO,KAAxBD,CACbH,MAAA,CAAaA,CAAb,CACA,OAAOC,EAAAI,KAAA,CAAS,EAAT,CAJoB,CAmE7BC,QAASA,EAAO,CAACC,CAAD,CAAM,CAAA,IAChBC,EAAM,EAAIC,EAAAA,CAAQF,CAAAG,MAAA,CAAU,GAAV,CAAtB,KAAsCC,CACtC,KAAKA,CAAL,CAAS,CAAT,CAAYA,CAAZ,CAAgBF,CAAAG,OAAhB,CAA8BD,CAAA,EAA9B,CAAmCH,CAAA,CAAIC,CAAA,CAAME,CAAN,CAAJ,CAAA,CAAgB,CAAA,CACnD,OAAOH,EAHa,CAmBtBK,QAASA,EAAU,CAAEC,CAAF,CAAQC,CAAR,CAAkB,CAiFnCC,QAASA,EAAa,CAAEC,CAAF,CAAOC,CAAP,CAAgBC,CAAhB,CAAsBC,CAAtB,CAA8B,CAClDF,CAAA,CAAUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,IAAKI,CAAA,CAAeJ,CAAf,CAAL,CACE,IAAA,CAAQK,CAAAC,KAAA,EAAR,EAAwBC,CAAA,CAAgBF,CAAAC,KAAA,EAAhB,CAAxB,CAAA,CACEE,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CAICG,EAAA,CAAwBT,CAAxB,CAAL,EAA0CK,CAAAC,KAAA,EAA1C,EAA0DN,CAA1D,EACEQ,CAAA,CAAa,EAAb,CAAiBR,CAAjB,CAKF,EAFAE,CAEA,CAFQQ,CAAA,CAAcV,CAAd,CAER,EAFmC,CAAC,CAACE,CAErC,GACEG,CAAAM,KAAA,CAAYX,CAAZ,CAEF,KAAIY,EAAQ,EAEZX,EAAAY,QAAA,CAAaC,CAAb,CACE,QAAQ,CAACC,CAAD,CAAQC,CAAR,CAAcC,CAAd,CAAiCC,CAAjC,CAAoDC,CAApD,CAAmE,CAMzEP,CAAA,CAAMI,CAAN,CAAA,CAAcI,CAAA,CALFH,CAKE,EAJTC,CAIS,EAHTC,CAGS,EAFT,EAES,CAN2D,CAD7E,CASItB,EAAAwB,MAAJ,EAAmBxB,CAAAwB,MAAA,CAAerB,CAAf,CAAwBY,CAAxB,CAA+BV,CAA/B,CA5B+B,CA+BpDM,QAASA,EAAW,CAAET,CAAF,CAAOC,CAAP,CAAiB,CAAA,IAC/BsB,EAAM,CADyB,CACtB7B,CAEb,IADAO,CACA,CADUrB,CAAAwB,UAAA,CAAkBH,CAAlB,CACV,CAEE,IAAMsB,CAAN,CAAYjB,CAAAX,OAAZ,CAA2B,CAA3B,CAAqC,CAArC,EAA8B4B,CAA9B,EACOjB,CAAA,CAAOiB,CAAP,CADP,EACuBtB,CADvB,CAAwCsB,CAAA,EAAxC;AAIF,GAAY,CAAZ,EAAKA,CAAL,CAAgB,CAEd,IAAM7B,CAAN,CAAUY,CAAAX,OAAV,CAAyB,CAAzB,CAA4BD,CAA5B,EAAiC6B,CAAjC,CAAsC7B,CAAA,EAAtC,CACMI,CAAA0B,IAAJ,EAAiB1B,CAAA0B,IAAA,CAAalB,CAAA,CAAOZ,CAAP,CAAb,CAGnBY,EAAAX,OAAA,CAAe4B,CAND,CATmB,CAhHF,IAC/BE,CAD+B,CACxB1C,CADwB,CACVuB,EAAQ,EADE,CACEC,EAAOV,CAG5C,KAFAS,CAAAC,KAEA,CAFamB,QAAQ,EAAG,CAAE,MAAOpB,EAAA,CAAOA,CAAAX,OAAP,CAAsB,CAAtB,CAAT,CAExB,CAAQE,CAAR,CAAA,CAAe,CACbd,CAAA,CAAQ,CAAA,CAGR,IAAMuB,CAAAC,KAAA,EAAN,EAAuBoB,CAAA,CAAiBrB,CAAAC,KAAA,EAAjB,CAAvB,CAmDEV,CASA,CATOA,CAAAiB,QAAA,CAAiBc,MAAJ,CAAW,kBAAX,CAAgCtB,CAAAC,KAAA,EAAhC,CAA+C,QAA/C,CAAyD,GAAzD,CAAb,CACL,QAAQ,CAACsB,CAAD,CAAMC,CAAN,CAAW,CACjBA,CAAA,CAAOA,CAAAhB,QAAA,CAAaiB,CAAb,CAA6B,IAA7B,CAAAjB,QAAA,CAA2CkB,CAA3C,CAAyD,IAAzD,CAEHlC,EAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeS,CAAf,CAAf,CAEnB,OAAO,EALU,CADd,CASP,CAAArB,CAAA,CAAa,EAAb,CAAiBH,CAAAC,KAAA,EAAjB,CA5DF,KAAyD,CAGvD,GAA8B,CAA9B,GAAKV,CAAAoC,QAAA,CAAa,SAAb,CAAL,CAEER,CAEA,CAFQ5B,CAAAoC,QAAA,CAAa,IAAb,CAAmB,CAAnB,CAER,CAAc,CAAd,EAAKR,CAAL,EAAmB5B,CAAAqC,YAAA,CAAiB,QAAjB,CAAwBT,CAAxB,CAAnB,GAAsDA,CAAtD,GACM3B,CAAAqC,QAEJ,EAFqBrC,CAAAqC,QAAA,CAAiBtC,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAAjB,CAErB,CADA5B,CACA,CADOA,CAAAuC,UAAA,CAAgBX,CAAhB,CAAwB,CAAxB,CACP,CAAA1C,CAAA,CAAQ,CAAA,CAHV,CAJF,KAUO,IAAKsD,CAAAC,KAAA,CAAoBzC,CAApB,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYqB,CAAZ,CAER,CACExC,CACA;AADOA,CAAAiB,QAAA,CAAcE,CAAA,CAAM,CAAN,CAAd,CAAyB,EAAzB,CACP,CAAAjC,CAAA,CAAQ,CAAA,CAFV,CAHK,IAQA,IAAKwD,CAAAD,KAAA,CAA4BzC,CAA5B,CAAL,CAGL,IAFAmB,CAEA,CAFQnB,CAAAmB,MAAA,CAAYwB,CAAZ,CAER,CACE3C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB0B,CAAlB,CAAkC/B,CAAlC,CACA,CAAA1B,CAAA,CAAQ,CAAA,CAHV,CAHK,IAUK0D,EAAAH,KAAA,CAAsBzC,CAAtB,CAAL,GACLmB,CADK,CACGnB,CAAAmB,MAAA,CAAY0B,CAAZ,CADH,IAIH7C,CAEA,CAFOA,CAAAuC,UAAA,CAAgBpB,CAAA,CAAM,CAAN,CAAArB,OAAhB,CAEP,CADAqB,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAkB4B,CAAlB,CAAoC3C,CAApC,CACA,CAAAhB,CAAA,CAAQ,CAAA,CANL,CAUFA,EAAL,GACE0C,CAKA,CALQ5B,CAAAoC,QAAA,CAAa,GAAb,CAKR,CAHIH,CAGJ,CAHmB,CAAR,CAAAL,CAAA,CAAY5B,CAAZ,CAAmBA,CAAAuC,UAAA,CAAgB,CAAhB,CAAmBX,CAAnB,CAG9B,CAFA5B,CAEA,CAFe,CAAR,CAAA4B,CAAA,CAAY,EAAZ,CAAiB5B,CAAAuC,UAAA,CAAgBX,CAAhB,CAExB,CAAI3B,CAAAf,MAAJ,EAAmBe,CAAAf,MAAA,CAAesC,CAAA,CAAeS,CAAf,CAAf,CANrB,CAzCuD,CA+DzD,GAAKjC,CAAL,EAAaU,CAAb,CACE,KAAMoC,EAAA,CAAgB,UAAhB,CAC4C9C,CAD5C,CAAN,CAGFU,CAAA,CAAOV,CAvEM,CA2EfY,CAAA,EA/EmC,CA2IrCY,QAASA,EAAc,CAACuB,CAAD,CAAQ,CAC7B,GAAI,CAACA,CAAL,CAAc,MAAO,EAIrB,KAAIC,EAAQC,CAAAC,KAAA,CAAaH,CAAb,CACRI,EAAAA,CAAcH,CAAA,CAAM,CAAN,CAClB,KAAII,EAAaJ,CAAA,CAAM,CAAN,CAEjB,IADIK,CACJ,CADcL,CAAA,CAAM,CAAN,CACd,CACEM,CAAAC,UAKA,CALoBF,CAAApC,QAAA,CAAgB,IAAhB,CAAqB,MAArB,CAKpB,CAAAoC,CAAA,CAAU,aAAA,EAAiBC,EAAjB,CACRA,CAAAE,YADQ,CACgBF,CAAAG,UAE5B,OAAON,EAAP,CAAqBE,CAArB,CAA+BD,CAlBF,CA4B/BM,QAASA,EAAc,CAACX,CAAD,CAAQ,CAC7B,MAAOA,EAAA9B,QAAA,CACG,IADH;AACS,OADT,CAAAA,QAAA,CAEG0C,CAFH,CAE4B,QAAQ,CAACZ,CAAD,CAAO,CAC9C,MAAO,IAAP,CAAcA,CAAAa,WAAA,CAAiB,CAAjB,CAAd,CAAoC,GADU,CAF3C,CAAA3C,QAAA,CAKG,IALH,CAKS,MALT,CAAAA,QAAA,CAMG,IANH,CAMS,MANT,CADsB,CAoB/B7B,QAASA,EAAkB,CAACD,CAAD,CAAM0E,CAAN,CAAmB,CAC5C,IAAIC,EAAS,CAAA,CAAb,CACIC,EAAMhF,CAAAiF,KAAA,CAAa7E,CAAb,CAAkBA,CAAA4B,KAAlB,CACV,OAAO,OACEU,QAAQ,CAACtB,CAAD,CAAMa,CAAN,CAAaV,CAAb,CAAmB,CAChCH,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD2D,EAAAA,CAAL,EAAehC,CAAA,CAAgB3B,CAAhB,CAAf,GACE2D,CADF,CACW3D,CADX,CAGK2D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAc9D,CAAd,CAAf,GACE4D,CAAA,CAAI,GAAJ,CAcA,CAbAA,CAAA,CAAI5D,CAAJ,CAaA,CAZApB,CAAAmF,QAAA,CAAgBlD,CAAhB,CAAuB,QAAQ,CAAC+B,CAAD,CAAQoB,CAAR,CAAY,CACzC,IAAIC,EAAKrF,CAAAwB,UAAA,CAAkB4D,CAAlB,CAAT,CACIE,EAAmB,KAAnBA,GAAWlE,CAAXkE,EAAqC,KAArCA,GAA4BD,CAA5BC,EAAyD,YAAzDA,GAAgDD,CAC3B,EAAA,CAAzB,GAAIE,CAAA,CAAWF,CAAX,CAAJ,EACsB,CAAA,CADtB,GACGG,CAAA,CAASH,CAAT,CADH,EAC8B,CAAAP,CAAA,CAAad,CAAb,CAAoBsB,CAApB,CAD9B,GAEEN,CAAA,CAAI,GAAJ,CAIA,CAHAA,CAAA,CAAII,CAAJ,CAGA,CAFAJ,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIL,CAAA,CAAeX,CAAf,CAAJ,CACA,CAAAgB,CAAA,CAAI,GAAJ,CANF,CAHyC,CAA3C,CAYA,CAAAA,CAAA,CAAIzD,CAAA,CAAQ,IAAR,CAAe,GAAnB,CAfF,CALgC,CAD7B,KAwBAqB,QAAQ,CAACxB,CAAD,CAAK,CACdA,CAAA,CAAMpB,CAAAwB,UAAA,CAAkBJ,CAAlB,CACD2D,EAAL,EAAsC,CAAA,CAAtC,GAAeG,CAAA,CAAc9D,CAAd,CAAf,GACE4D,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAI5D,CAAJ,CACA,CAAA4D,CAAA,CAAI,GAAJ,CAHF,CAKI5D,EAAJ,EAAW2D,CAAX,GACEA,CADF,CACW,CAAA,CADX,CAPc,CAxBb,OAmCE5E,QAAQ,CAACA,CAAD,CAAO,CACb4E,CAAL;AACEC,CAAA,CAAIL,CAAA,CAAexE,CAAf,CAAJ,CAFgB,CAnCjB,CAHqC,CAja9C,IAAI4D,EAAkB/D,CAAAyF,SAAA,CAAiB,WAAjB,CAAtB,CAyJI3B,EACG,4FA1JP,CA2JEF,EAAiB,2BA3JnB,CA4JEzB,EAAc,yEA5JhB,CA6JE0B,EAAmB,IA7JrB,CA8JEF,EAAyB,SA9J3B,CA+JER,EAAiB,qBA/JnB,CAgKEM,EAAiB,qBAhKnB,CAiKEL,EAAe,yBAjKjB,CAmKEwB,EAA0B,gBAnK5B,CA4KI7C,EAAetB,CAAA,CAAQ,wBAAR,CAIfiF,EAAAA,CAA8BjF,CAAA,CAAQ,gDAAR,CAC9BkF,EAAAA,CAA+BlF,CAAA,CAAQ,OAAR,CADnC,KAEIqB,EAAyB9B,CAAA4F,OAAA,CAAe,EAAf,CACeD,CADf,CAEeD,CAFf,CAF7B,CAOIjE,EAAgBzB,CAAA4F,OAAA,CAAe,EAAf,CAAmBF,CAAnB,CAAgDjF,CAAA,CAAQ,4KAAR,CAAhD,CAPpB;AAYImB,EAAiB5B,CAAA4F,OAAA,CAAe,EAAf,CAAmBD,CAAnB,CAAiDlF,CAAA,CAAQ,2JAAR,CAAjD,CAZrB,CAkBIsC,EAAkBtC,CAAA,CAAQ,cAAR,CAlBtB,CAoBIyE,EAAgBlF,CAAA4F,OAAA,CAAe,EAAf,CACe7D,CADf,CAEeN,CAFf,CAGeG,CAHf,CAIeE,CAJf,CApBpB,CA2BI0D,EAAW/E,CAAA,CAAQ,0CAAR,CA3Bf,CA4BI8E,EAAavF,CAAA4F,OAAA,CAAe,EAAf,CAAmBJ,CAAnB,CAA6B/E,CAAA,CAC1C,ySAD0C,CAA7B,CA5BjB;AA0LI8D,EAAUsB,QAAAC,cAAA,CAAuB,KAAvB,CA1Ld,CA2LI5B,EAAU,wBAsGdlE,EAAA+F,OAAA,CAAe,YAAf,CAA6B,EAA7B,CAAAC,SAAA,CAA0C,WAA1C,CA7UAC,QAA0B,EAAG,CAC3B,IAAAC,KAAA,CAAY,CAAC,eAAD,CAAkB,QAAQ,CAACC,CAAD,CAAgB,CACpD,MAAO,SAAQ,CAAClF,CAAD,CAAO,CACpB,IAAIb,EAAM,EACVY,EAAA,CAAWC,CAAX,CAAiBZ,CAAA,CAAmBD,CAAnB,CAAwB,QAAQ,CAACgG,CAAD,CAAMd,CAAN,CAAe,CAC9D,MAAO,CAAC,SAAA5B,KAAA,CAAeyC,CAAA,CAAcC,CAAd,CAAmBd,CAAnB,CAAf,CADsD,CAA/C,CAAjB,CAGA,OAAOlF,EAAAI,KAAA,CAAS,EAAT,CALa,CAD8B,CAA1C,CADe,CA6U7B,CAuGAR,EAAA+F,OAAA,CAAe,YAAf,CAAAM,OAAA,CAAoC,OAApC,CAA6C,CAAC,WAAD,CAAc,QAAQ,CAACC,CAAD,CAAY,CAAA,IACzEC,EACE,mEAFuE,CAGzEC,EAAgB,UAEpB,OAAO,SAAQ,CAACtD,CAAD,CAAOuD,CAAP,CAAe,CAoB5BC,QAASA,EAAO,CAACxD,CAAD,CAAO,CAChBA,CAAL,EAGAjC,CAAAe,KAAA,CAAU9B,CAAA,CAAagD,CAAb,CAAV,CAJqB,CAOvByD,QAASA,EAAO,CAACC,CAAD,CAAM1D,CAAN,CAAY,CAC1BjC,CAAAe,KAAA,CAAU,KAAV,CACIhC,EAAA6G,UAAA,CAAkBJ,CAAlB,CAAJ;CACExF,CAAAe,KAAA,CAAU,UAAV,CAEA,CADAf,CAAAe,KAAA,CAAUyE,CAAV,CACA,CAAAxF,CAAAe,KAAA,CAAU,IAAV,CAHF,CAKAf,EAAAe,KAAA,CAAU,QAAV,CACAf,EAAAe,KAAA,CAAU4E,CAAV,CACA3F,EAAAe,KAAA,CAAU,IAAV,CACA0E,EAAA,CAAQxD,CAAR,CACAjC,EAAAe,KAAA,CAAU,MAAV,CAX0B,CA1B5B,GAAI,CAACkB,CAAL,CAAW,MAAOA,EAMlB,KALA,IAAId,CAAJ,CACI0E,EAAM5D,CADV,CAEIjC,EAAO,EAFX,CAGI2F,CAHJ,CAII9F,CACJ,CAAQsB,CAAR,CAAgB0E,CAAA1E,MAAA,CAAUmE,CAAV,CAAhB,CAAA,CAEEK,CAMA,CANMxE,CAAA,CAAM,CAAN,CAMN,CAJIA,CAAA,CAAM,CAAN,CAIJ,EAJgBA,CAAA,CAAM,CAAN,CAIhB,GAJ0BwE,CAI1B,CAJgC,SAIhC,CAJ4CA,CAI5C,EAHA9F,CAGA,CAHIsB,CAAAS,MAGJ,CAFA6D,CAAA,CAAQI,CAAAC,OAAA,CAAW,CAAX,CAAcjG,CAAd,CAAR,CAEA,CADA6F,CAAA,CAAQC,CAAR,CAAaxE,CAAA,CAAM,CAAN,CAAAF,QAAA,CAAiBsE,CAAjB,CAAgC,EAAhC,CAAb,CACA,CAAAM,CAAA,CAAMA,CAAAtD,UAAA,CAAc1C,CAAd,CAAkBsB,CAAA,CAAM,CAAN,CAAArB,OAAlB,CAER2F,EAAA,CAAQI,CAAR,CACA,OAAOR,EAAA,CAAUrF,CAAAT,KAAA,CAAU,EAAV,CAAV,CAlBqB,CAL+C,CAAlC,CAA7C,CA1jBsC,CAArC,CAAA,CA2mBET,MA3mBF,CA2mBUA,MAAAC,QA3mBV;",
"sources":["angular-sanitize.js"],
"names":["window","angular","undefined","sanitizeText","chars","buf","htmlSanitizeWriter","writer","noop","join","makeMap","str","obj","items","split","i","length","htmlParser","html","handler","parseStartTag","tag","tagName","rest","unary","lowercase","blockElements","stack","last","inlineElements","parseEndTag","optionalEndTagElements","voidElements","push","attrs","replace","ATTR_REGEXP","match","name","doubleQuotedValue","singleQuotedValue","unquotedValue","decodeEntities","start","pos","end","index","stack.last","specialElements","RegExp","all","text","COMMENT_REGEXP","CDATA_REGEXP","indexOf","lastIndexOf","comment","substring","DOCTYPE_REGEXP","test","BEGING_END_TAGE_REGEXP","END_TAG_REGEXP","BEGIN_TAG_REGEXP","START_TAG_REGEXP","$sanitizeMinErr","value","parts","spaceRe","exec","spaceBefore","spaceAfter","content","hiddenPre","innerHTML","textContent","innerText","encodeEntities","NON_ALPHANUMERIC_REGEXP","charCodeAt","uriValidator","ignore","out","bind","validElements","forEach","key","lkey","isImage","validAttrs","uriAttrs","$$minErr","optionalEndTagBlockElements","optionalEndTagInlineElements","extend","document","createElement","module","provider","$SanitizeProvider","$get","$$sanitizeUri","uri","filter","$sanitize","LINKY_URL_REGEXP","MAILTO_REGEXP","target","addText","addLink","url","isDefined","raw","substr"]
}
diff --git a/awx/ui/static/lib/angular-sanitize/bower.json b/awx/ui/static/lib/angular-sanitize/bower.json
new file mode 100644
index 0000000000..410f4f9f8f
--- /dev/null
+++ b/awx/ui/static/lib/angular-sanitize/bower.json
@@ -0,0 +1,8 @@
+{
+ "name": "angular-sanitize",
+ "version": "1.2.12",
+ "main": "./angular-sanitize.js",
+ "dependencies": {
+ "angular": "1.2.12"
+ }
+}
diff --git a/awx/ui/static/lib/angular/.bower.json b/awx/ui/static/lib/angular/.bower.json
new file mode 100644
index 0000000000..a35584603c
--- /dev/null
+++ b/awx/ui/static/lib/angular/.bower.json
@@ -0,0 +1,17 @@
+{
+ "name": "angular",
+ "version": "1.2.12",
+ "main": "./angular.js",
+ "dependencies": {},
+ "homepage": "https://github.com/angular/bower-angular",
+ "_release": "1.2.12",
+ "_resolution": {
+ "type": "version",
+ "tag": "v1.2.12",
+ "commit": "fba58ce358fa9ab5812cbc10f80cd30eb9510519"
+ },
+ "_source": "git://github.com/angular/bower-angular.git",
+ "_target": "~1.2.12",
+ "_originalSource": "angular",
+ "_direct": true
+}
\ No newline at end of file
diff --git a/awx/ui/static/lib/angular/README.md b/awx/ui/static/lib/angular/README.md
new file mode 100644
index 0000000000..fc0c09987e
--- /dev/null
+++ b/awx/ui/static/lib/angular/README.md
@@ -0,0 +1,48 @@
+# bower-angular
+
+This repo is for distribution on `bower`. The source for this module is in the
+[main AngularJS repo](https://github.com/angular/angular.js).
+Please file issues and pull requests against that repo.
+
+## Install
+
+Install with `bower`:
+
+```shell
+bower install angular
+```
+
+Add a `
+```
+
+## Documentation
+
+Documentation is available on the
+[AngularJS docs site](http://docs.angularjs.org/).
+
+## License
+
+The MIT License
+
+Copyright (c) 2010-2012 Google, Inc. http://angularjs.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/awx/ui/static/lib/angular-1.2.9/angular-csp.css b/awx/ui/static/lib/angular/angular-csp.css
similarity index 100%
rename from awx/ui/static/lib/angular-1.2.9/angular-csp.css
rename to awx/ui/static/lib/angular/angular-csp.css
diff --git a/awx/ui/static/lib/angular/angular.js b/awx/ui/static/lib/angular/angular.js
old mode 100755
new mode 100644
index 2a783722c1..e70ad20eaf
--- a/awx/ui/static/lib/angular/angular.js
+++ b/awx/ui/static/lib/angular/angular.js
@@ -1,10 +1,167 @@
/**
- * @license AngularJS v1.1.4
- * (c) 2010-2012 Google, Inc. http://angularjs.org
+ * @license AngularJS v1.2.12
+ * (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
-(function(window, document, undefined) {
-'use strict';
+(function(window, document, undefined) {'use strict';
+
+/**
+ * @description
+ *
+ * This object provides a utility for producing rich Error messages within
+ * Angular. It can be called as follows:
+ *
+ * var exampleMinErr = minErr('example');
+ * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
+ *
+ * The above creates an instance of minErr in the example namespace. The
+ * resulting error will have a namespaced error code of example.one. The
+ * resulting error will replace {0} with the value of foo, and {1} with the
+ * value of bar. The object is not restricted in the number of arguments it can
+ * take.
+ *
+ * If fewer arguments are specified than necessary for interpolation, the extra
+ * interpolation markers will be preserved in the final string.
+ *
+ * Since data will be parsed statically during a build step, some restrictions
+ * are applied with respect to how minErr instances are created and called.
+ * Instances should have names of the form namespaceMinErr for a minErr created
+ * using minErr('namespace') . Error codes, namespaces and template strings
+ * should all be static strings, not variables or general expressions.
+ *
+ * @param {string} module The namespace to use for the new minErr instance.
+ * @returns {function(string, string, ...): Error} instance
+ */
+
+function minErr(module) {
+ return function () {
+ var code = arguments[0],
+ prefix = '[' + (module ? module + ':' : '') + code + '] ',
+ template = arguments[1],
+ templateArgs = arguments,
+ stringify = function (obj) {
+ if (typeof obj === 'function') {
+ return obj.toString().replace(/ \{[\s\S]*$/, '');
+ } else if (typeof obj === 'undefined') {
+ return 'undefined';
+ } else if (typeof obj !== 'string') {
+ return JSON.stringify(obj);
+ }
+ return obj;
+ },
+ message, i;
+
+ message = prefix + template.replace(/\{\d+\}/g, function (match) {
+ var index = +match.slice(1, -1), arg;
+
+ if (index + 2 < templateArgs.length) {
+ arg = templateArgs[index + 2];
+ if (typeof arg === 'function') {
+ return arg.toString().replace(/ ?\{[\s\S]*$/, '');
+ } else if (typeof arg === 'undefined') {
+ return 'undefined';
+ } else if (typeof arg !== 'string') {
+ return toJson(arg);
+ }
+ return arg;
+ }
+ return match;
+ });
+
+ message = message + '\nhttp://errors.angularjs.org/1.2.12/' +
+ (module ? module + '/' : '') + code;
+ for (i = 2; i < arguments.length; i++) {
+ message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
+ encodeURIComponent(stringify(arguments[i]));
+ }
+
+ return new Error(message);
+ };
+}
+
+/* We need to tell jshint what variables are being exported */
+/* global
+ -angular,
+ -msie,
+ -jqLite,
+ -jQuery,
+ -slice,
+ -push,
+ -toString,
+ -ngMinErr,
+ -_angular,
+ -angularModule,
+ -nodeName_,
+ -uid,
+
+ -lowercase,
+ -uppercase,
+ -manualLowercase,
+ -manualUppercase,
+ -nodeName_,
+ -isArrayLike,
+ -forEach,
+ -sortedKeys,
+ -forEachSorted,
+ -reverseParams,
+ -nextUid,
+ -setHashKey,
+ -extend,
+ -int,
+ -inherit,
+ -noop,
+ -identity,
+ -valueFn,
+ -isUndefined,
+ -isDefined,
+ -isObject,
+ -isString,
+ -isNumber,
+ -isDate,
+ -isArray,
+ -isFunction,
+ -isRegExp,
+ -isWindow,
+ -isScope,
+ -isFile,
+ -isBoolean,
+ -trim,
+ -isElement,
+ -makeMap,
+ -map,
+ -size,
+ -includes,
+ -indexOf,
+ -arrayRemove,
+ -isLeafNode,
+ -copy,
+ -shallowCopy,
+ -equals,
+ -csp,
+ -concat,
+ -sliceArgs,
+ -bind,
+ -toJsonReplacer,
+ -toJson,
+ -fromJson,
+ -toBoolean,
+ -startingTag,
+ -tryDecodeURIComponent,
+ -parseKeyValue,
+ -toKeyValue,
+ -encodeUriSegment,
+ -encodeUriQuery,
+ -angularInit,
+ -bootstrap,
+ -snake_case,
+ -bindJQuery,
+ -assertArg,
+ -assertArgFn,
+ -assertNotHasOwnProperty,
+ -getter,
+ -getBlockElements,
+
+*/
////////////////////////////////////
@@ -33,11 +190,13 @@ var uppercase = function(string){return isString(string) ? string.toUpperCase()
var manualLowercase = function(s) {
+ /* jshint bitwise: false */
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
+ /* jshint bitwise: false */
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
@@ -54,12 +213,13 @@ if ('i' !== 'I'.toLowerCase()) {
var /** holds major version number for IE or NaN for real browsers */
- msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
+ msie,
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
+ ngMinErr = minErr('ng'),
_angular = window.angular,
@@ -70,21 +230,34 @@ var /** holds major version number for IE or NaN for real browsers */
uid = ['0', '0', '0'];
/**
- * @ngdoc function
- * @name angular.noConflict
- * @function
- *
- * @description
- * Restores the previous global value of angular and returns the current instance. Other libraries may already use the
- * angular namespace. Or a previous version of angular is already loaded on the page. In these cases you may want to
- * restore the previous namespace and keep a reference to angular.
- *
- * @return {Object} The current angular namespace
+ * IE 11 changed the format of the UserAgent string.
+ * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
*/
-function noConflict() {
- var a = window.angular;
- window.angular = _angular;
- return a;
+msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
+if (isNaN(msie)) {
+ msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
+}
+
+
+/**
+ * @private
+ * @param {*} obj
+ * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
+ * String ...)
+ */
+function isArrayLike(obj) {
+ if (obj == null || isWindow(obj)) {
+ return false;
+ }
+
+ var length = obj.length;
+
+ if (obj.nodeType === 1 && length) {
+ return true;
+ }
+
+ return isString(obj) || isArray(obj) || length === 0 ||
+ typeof length === 'number' && length > 0 && (length - 1) in obj;
}
/**
@@ -98,7 +271,8 @@ function noConflict() {
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
- * Note: this function was previously known as `angular.foreach`.
+ * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
+ * using the `hasOwnProperty` method.
*
*/
@@ -310,7 +475,7 @@ function valueFn(value) {return function() {return value;};}
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
-function isUndefined(value){return typeof value == 'undefined';}
+function isUndefined(value){return typeof value === 'undefined';}
/**
@@ -324,7 +489,7 @@ function isUndefined(value){return typeof value == 'undefined';}
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
-function isDefined(value){return typeof value != 'undefined';}
+function isDefined(value){return typeof value !== 'undefined';}
/**
@@ -339,7 +504,7 @@ function isDefined(value){return typeof value != 'undefined';}
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
-function isObject(value){return value != null && typeof value == 'object';}
+function isObject(value){return value != null && typeof value === 'object';}
/**
@@ -353,7 +518,7 @@ function isObject(value){return value != null && typeof value == 'object';}
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
-function isString(value){return typeof value == 'string';}
+function isString(value){return typeof value === 'string';}
/**
@@ -367,7 +532,7 @@ function isString(value){return typeof value == 'string';}
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
-function isNumber(value){return typeof value == 'number';}
+function isNumber(value){return typeof value === 'number';}
/**
@@ -382,7 +547,7 @@ function isNumber(value){return typeof value == 'number';}
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
- return toString.apply(value) == '[object Date]';
+ return toString.call(value) === '[object Date]';
}
@@ -398,7 +563,7 @@ function isDate(value){
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
- return toString.apply(value) == '[object Array]';
+ return toString.call(value) === '[object Array]';
}
@@ -413,7 +578,19 @@ function isArray(value) {
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
-function isFunction(value){return typeof value == 'function';}
+function isFunction(value){return typeof value === 'function';}
+
+
+/**
+ * Determines if a value is a regular expression object.
+ *
+ * @private
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `RegExp`.
+ */
+function isRegExp(value) {
+ return toString.call(value) === '[object RegExp]';
+}
/**
@@ -434,18 +611,29 @@ function isScope(obj) {
function isFile(obj) {
- return toString.apply(obj) === '[object File]';
+ return toString.call(obj) === '[object File]';
}
function isBoolean(value) {
- return typeof value == 'boolean';
+ return typeof value === 'boolean';
}
-function trim(value) {
- return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
-}
+var trim = (function() {
+ // native trim is way faster: http://jsperf.com/angular-trim-test
+ // but IE doesn't have it... :-(
+ // TODO: we should move this into IE/ES5 polyfill
+ if (!String.prototype.trim) {
+ return function(value) {
+ return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
+ };
+ }
+ return function(value) {
+ return isString(value) ? value.trim() : value;
+ };
+})();
+
/**
* @ngdoc function
@@ -459,9 +647,9 @@ function trim(value) {
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
- return node &&
+ return !!(node &&
(node.nodeName // we are a direct element
- || (node.bind && node.find)); // we have a bind and find method part of jQuery API
+ || (node.on && node.find))); // we have an on and find method part of jQuery API
}
/**
@@ -511,17 +699,17 @@ function map(obj, iterator, context) {
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
- var size = 0, key;
+ var count = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
- size++;
+ count++;
}
- return size;
+ return count;
}
@@ -532,7 +720,7 @@ function includes(array, obj) {
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
- for ( var i = 0; i < array.length; i++) {
+ for (var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
@@ -568,19 +756,57 @@ function isLeafNode (node) {
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
- * * If `source` is not an object or array, `source` is returned.
- *
- * Note: this function is used to augment the Object type in Angular expressions. See
- * {@link ng.$filter} for more information about Angular arrays.
+ * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
+ * * If `source` is identical to 'destination' an exception will be thrown.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
+ *
+ * @example
+
+
+
+
+ Name:
+ E-mail:
+ Gender: male
+ female
+
+
+
+
form = {{user | json}}
+
master = {{master | json}}
+
+
+
+
+
*/
function copy(source, destination){
- if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
+ if (isWindow(source) || isScope(source)) {
+ throw ngMinErr('cpws',
+ "Can't copy! Making copies of Window or Scope instances is not supported.");
+ }
+
if (!destination) {
destination = source;
if (source) {
@@ -588,24 +814,29 @@ function copy(source, destination){
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
+ } else if (isRegExp(source)) {
+ destination = new RegExp(source.source);
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
- if (source === destination) throw Error("Can't copy equivalent objects or arrays");
+ if (source === destination) throw ngMinErr('cpi',
+ "Can't copy! Source and destination are identical.");
if (isArray(source)) {
destination.length = 0;
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
+ var h = destination.$$hashKey;
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
+ setHashKey(destination,h);
}
}
return destination;
@@ -618,7 +849,9 @@ function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
- if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
+ // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
+ // so we don't need to worry about using our custom hasOwnProperty here
+ if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
@@ -633,19 +866,23 @@ function shallowCopy(src, dst) {
* @function
*
* @description
- * Determines if two objects or two values are equivalent. Supports value types, arrays and
- * objects.
+ * Determines if two objects or two values are equivalent. Supports value types, regular
+ * expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
- * * Both objects or values are of the same type and all of their properties pass `===` comparison.
- * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
+ * * Both objects or values are of the same type and all of their properties are equal by
+ * comparing them with `angular.equals`.
+ * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
+ * * Both values represent the same regular expression (In JavasScript,
+ * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
+ * representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
- * Scope and DOMWindow objects are being compared only be identify (`===`).
+ * Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
@@ -659,6 +896,7 @@ function equals(o1, o2) {
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
+ if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for(key=0; key 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
@@ -737,7 +987,7 @@ function bind(self, fn) {
function toJsonReplacer(key, value) {
var val = value;
- if (/^\$+/.test(key)) {
+ if (typeof key === 'string' && key.charAt(0) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
@@ -757,13 +1007,15 @@ function toJsonReplacer(key, value) {
* @function
*
* @description
- * Serializes input into a JSON-formatted string.
+ * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
+ * stripped since angular uses this notation internally.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
- * @returns {string} Jsonified string representing `obj`.
+ * @returns {string|undefined} JSON-ified string representing `obj`.
*/
function toJson(obj, pretty) {
+ if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
@@ -787,7 +1039,9 @@ function fromJson(json) {
function toBoolean(value) {
- if (value && value.length !== 0) {
+ if (typeof value === 'function') {
+ value = true;
+ } else if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
@@ -804,7 +1058,7 @@ function startingTag(element) {
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
- element.html('');
+ element.empty();
} catch(e) {}
// As Per DOM Standards
var TEXT_NODE = 3;
@@ -823,6 +1077,23 @@ function startingTag(element) {
/////////////////////////////////////////////////
+/**
+ * Tries to decode the URI component without throwing an exception.
+ *
+ * @private
+ * @param str value potential URI component to check.
+ * @returns {boolean} True if `value` can be decoded
+ * with the decodeURIComponent function.
+ */
+function tryDecodeURIComponent(value) {
+ try {
+ return decodeURIComponent(value);
+ } catch(e) {
+ // Ignore any invalid uri component
+ }
+}
+
+
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
@@ -830,10 +1101,19 @@ function startingTag(element) {
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
- if (keyValue) {
+ if ( keyValue ) {
key_value = keyValue.split('=');
- key = decodeURIComponent(key_value[0]);
- obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
+ key = tryDecodeURIComponent(key_value[0]);
+ if ( isDefined(key) ) {
+ var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
+ if (!obj[key]) {
+ obj[key] = val;
+ } else if(isArray(obj[key])) {
+ obj[key].push(val);
+ } else {
+ obj[key] = [obj[key],val];
+ }
+ }
}
});
return obj;
@@ -842,7 +1122,15 @@ function parseKeyValue(/**string*/keyValue) {
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
- parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
+ if (isArray(value)) {
+ forEach(value, function(arrayValue) {
+ parts.push(encodeUriQuery(key, true) +
+ (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
+ });
+ } else {
+ parts.push(encodeUriQuery(key, true) +
+ (value === true ? '' : '=' + encodeUriQuery(value, true)));
+ }
});
return parts.length ? parts.join('&') : '';
}
@@ -898,22 +1186,38 @@ function encodeUriQuery(val, pctEncodeSpaces) {
*
* @description
*
- * Use this directive to auto-bootstrap on application. Only
- * one directive can be used per HTML document. The directive
- * designates the root of the application and is typically placed
- * at the root of the page.
+ * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
+ * designates the **root element** of the application and is typically placed near the root element
+ * of the page - e.g. on the `` or `` tags.
*
- * In the example below if the `ngApp` directive would not be placed
- * on the `html` element then the document would not be compiled
- * and the `{{ 1+2 }}` would not be resolved to `3`.
+ * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
+ * found in the document will be used to define the root element to auto-bootstrap as an
+ * application. To run multiple applications in an HTML document you must manually bootstrap them using
+ * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
*
- * `ngApp` is the easiest way to bootstrap an application.
+ * You can specify an **AngularJS module** to be used as the root module for the application. This
+ * module will be loaded into the {@link AUTO.$injector} when the application is bootstrapped and
+ * should contain the application code needed or have dependencies on other modules that will
+ * contain the code. See {@link angular.module} for more information.
*
-
-
- I can add: 1 + 2 = {{ 1+2 }}
-
-
+ * In the example below if the `ngApp` directive were not placed on the `html` element then the
+ * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
+ * would not be resolved to `3`.
+ *
+ * `ngApp` is the easiest, and most common, way to bootstrap an application.
+ *
+
+
+
+ I can add: {{a}} + {{b}} = {{ a+b }}
+
+
+ angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
+ $scope.a = 1;
+ $scope.b = 2;
+ });
+
+
*
*/
function angularInit(element, bootstrap) {
@@ -968,21 +1272,33 @@ function angularInit(element, bootstrap) {
*
* See: {@link guide/bootstrap Bootstrap}
*
+ * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
+ * They must use {@link api/ng.directive:ngApp ngApp}.
+ *
* @param {Element} element DOM element which is the root of angular application.
- * @param {Array=} modules an array of module declarations. See: {@link angular.module modules}
+ * @param {Array=} modules an array of modules to load into the application.
+ * Each item in the array should be the name of a predefined module or a (DI annotated)
+ * function that will be invoked by the injector as a run block.
+ * See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
- var resumeBootstrapInternal = function() {
+ var doBootstrap = function() {
element = jqLite(element);
+
+ if (element.injector()) {
+ var tag = (element[0] === document) ? 'document' : startingTag(element);
+ throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
+ }
+
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
- injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
- function(scope, element, compile, injector) {
+ injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
+ function(scope, element, compile, injector, animate) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
@@ -995,7 +1311,7 @@ function bootstrap(element, modules) {
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
- return resumeBootstrapInternal();
+ return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
@@ -1003,7 +1319,7 @@ function bootstrap(element, modules) {
forEach(extraModules, function(module) {
modules.push(module);
});
- resumeBootstrapInternal();
+ doBootstrap();
};
}
@@ -1023,13 +1339,16 @@ function bindJQuery() {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
+ isolateScope: JQLitePrototype.isolateScope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
- JQLitePatchJQueryRemove('remove', true);
- JQLitePatchJQueryRemove('empty');
- JQLitePatchJQueryRemove('html');
+ // Method signature:
+ // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
+ jqLitePatchJQueryRemove('remove', true, true, false);
+ jqLitePatchJQueryRemove('empty', false, false, false);
+ jqLitePatchJQueryRemove('html', false, false, true);
} else {
jqLite = JQLite;
}
@@ -1037,11 +1356,11 @@ function bindJQuery() {
}
/**
- * throw error of the argument is falsy.
+ * throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
- throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
+ throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
}
return arg;
}
@@ -1056,6 +1375,68 @@ function assertArgFn(arg, name, acceptArrayAnnotation) {
return arg;
}
+/**
+ * throw error if the name given is hasOwnProperty
+ * @param {String} name the name to test
+ * @param {String} context the context in which the name is used, such as module or directive
+ */
+function assertNotHasOwnProperty(name, context) {
+ if (name === 'hasOwnProperty') {
+ throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
+ }
+}
+
+/**
+ * Return the value accessible from the object by path. Any undefined traversals are ignored
+ * @param {Object} obj starting object
+ * @param {string} path path to traverse
+ * @param {boolean=true} bindFnToScope
+ * @returns value as accessible by path
+ */
+//TODO(misko): this function needs to be removed
+function getter(obj, path, bindFnToScope) {
+ if (!path) return obj;
+ var keys = path.split('.');
+ var key;
+ var lastInstance = obj;
+ var len = keys.length;
+
+ for (var i = 0; i < len; i++) {
+ key = keys[i];
+ if (obj) {
+ obj = (lastInstance = obj)[key];
+ }
+ }
+ if (!bindFnToScope && isFunction(obj)) {
+ return bind(lastInstance, obj);
+ }
+ return obj;
+}
+
+/**
+ * Return the DOM siblings between the first and last node in the given array.
+ * @param {Array} array like object
+ * @returns jQlite object containing the elements
+ */
+function getBlockElements(nodes) {
+ var startNode = nodes[0],
+ endNode = nodes[nodes.length - 1];
+ if (startNode === endNode) {
+ return jqLite(startNode);
+ }
+
+ var element = startNode;
+ var elements = [element];
+
+ do {
+ element = element.nextSibling;
+ if (!element) break;
+ elements.push(element);
+ } while (element !== endNode);
+
+ return jqLite(elements);
+}
+
/**
* @ngdoc interface
* @name angular.Module
@@ -1066,11 +1447,19 @@ function assertArgFn(arg, name, acceptArrayAnnotation) {
function setupModuleLoader(window) {
+ var $injectorMinErr = minErr('$injector');
+ var ngMinErr = minErr('ng');
+
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
- return ensure(ensure(window, 'angular', Object), 'module', function() {
+ var angular = ensure(window, 'angular', Object);
+
+ // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
+ angular.$$minErr = angular.$$minErr || minErr;
+
+ return ensure(angular, 'module', function() {
/** @type {Object.} */
var modules = {};
@@ -1079,15 +1468,19 @@ function setupModuleLoader(window) {
* @name angular.module
* @description
*
- * The `angular.module` is a global place for creating and registering Angular modules. All
- * modules (angular core or 3rd party) that should be available to an application must be
+ * The `angular.module` is a global place for creating, registering and retrieving Angular
+ * modules.
+ * All modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
+ * When passed two or more arguments, a new module is created. If passed only one argument, an
+ * existing module (the name passed as the first argument to `module`) is retrieved.
+ *
*
* # Module
*
- * A module is a collocation of services, directives, filters, and configuration information. Module
- * is used to configure the {@link AUTO.$injector $injector}.
+ * A module is a collection of services, directives, filters, and configuration information.
+ * `angular.module` is used to configure the {@link AUTO.$injector $injector}.
*
*
* // Create a new module
@@ -1114,19 +1507,28 @@ function setupModuleLoader(window) {
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
- * @param {Array.=} requires If specified then new module is being created. If unspecified then the
- * the module is being retrieved for further configuration.
+ * @param {Array.=} requires If specified then new module is being created. If
+ * unspecified then the the module is being retrieved for further configuration.
* @param {Function} configFn Optional configuration function for the module. Same as
- * {@link angular.Module#config Module#config()}.
+ * {@link angular.Module#methods_config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
+ var assertNotHasOwnProperty = function(name, context) {
+ if (name === 'hasOwnProperty') {
+ throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
+ }
+ };
+
+ assertNotHasOwnProperty(name, 'module');
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
- throw Error('No module: ' + name);
+ throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
+ "the module name or forgot to load it. If registering a module ensure that you " +
+ "specify the dependencies as the second argument.", name);
}
/** @type {!Array.>} */
@@ -1149,7 +1551,8 @@ function setupModuleLoader(window) {
* @propertyOf angular.Module
* @returns {Array.} List of module names which must be loaded before this module.
* @description
- * Holds the list of modules which the injector will load before the current module is loaded.
+ * Holds the list of modules which the injector will load before the current module is
+ * loaded.
*/
requires: requires,
@@ -1168,7 +1571,8 @@ function setupModuleLoader(window) {
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
- * @param {Function} providerType Construction function for creating new instance of the service.
+ * @param {Function} providerType Construction function for creating new instance of the
+ * service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
@@ -1224,27 +1628,34 @@ function setupModuleLoader(window) {
* @name angular.Module#animation
* @methodOf angular.Module
* @param {string} name animation name
- * @param {Function} animationFactory Factory function for creating new instance of an animation.
+ * @param {Function} animationFactory Factory function for creating new instance of an
+ * animation.
* @description
*
- * Defines an animation hook that can be later used with {@link ng.directive:ngAnimate ngAnimate}
- * alongside {@link ng.directive:ngAnimate#Description common ng directives} as well as custom directives.
- *
- * module.animation('animation-name', function($inject1, $inject2) {
- * return {
- * //this gets called in preparation to setup an animation
- * setup : function(element) { ... },
+ * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
- * //this gets called once the animation is run
- * start : function(element, done, memo) { ... }
+ *
+ * Defines an animation hook that can be later used with
+ * {@link ngAnimate.$animate $animate} service and directives that use this service.
+ *
+ *
+ * module.animation('.animation-name', function($inject1, $inject2) {
+ * return {
+ * eventName : function(element, done) {
+ * //code to run the animation
+ * //once complete, then run done()
+ * return function cancellationFunction(element) {
+ * //code to cancel the animation
+ * }
+ * }
* }
* })
*
*
- * See {@link ng.$animationProvider#register $animationProvider.register()} and
- * {@link ng.directive:ngAnimate ngAnimate} for more information.
+ * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
+ * {@link ngAnimate ngAnimate module} for more information.
*/
- animation: invokeLater('$animationProvider', 'register'),
+ animation: invokeLater('$animateProvider', 'register'),
/**
* @ngdoc method
@@ -1261,7 +1672,8 @@ function setupModuleLoader(window) {
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
- * @param {string} name Controller name.
+ * @param {string|Object} name Controller name, or an object map of controllers where the
+ * keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
@@ -1272,11 +1684,12 @@ function setupModuleLoader(window) {
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
- * @param {string} name directive name
+ * @param {string|Object} name Directive name, or an object map of directives where the
+ * keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
- * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
+ * See {@link ng.$compileProvider#methods_directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
@@ -1323,7 +1736,7 @@ function setupModuleLoader(window) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
- }
+ };
}
});
};
@@ -1331,6 +1744,82 @@ function setupModuleLoader(window) {
}
+/* global
+ angularModule: true,
+ version: true,
+
+ $LocaleProvider,
+ $CompileProvider,
+
+ htmlAnchorDirective,
+ inputDirective,
+ inputDirective,
+ formDirective,
+ scriptDirective,
+ selectDirective,
+ styleDirective,
+ optionDirective,
+ ngBindDirective,
+ ngBindHtmlDirective,
+ ngBindTemplateDirective,
+ ngClassDirective,
+ ngClassEvenDirective,
+ ngClassOddDirective,
+ ngCspDirective,
+ ngCloakDirective,
+ ngControllerDirective,
+ ngFormDirective,
+ ngHideDirective,
+ ngIfDirective,
+ ngIncludeDirective,
+ ngIncludeFillContentDirective,
+ ngInitDirective,
+ ngNonBindableDirective,
+ ngPluralizeDirective,
+ ngRepeatDirective,
+ ngShowDirective,
+ ngStyleDirective,
+ ngSwitchDirective,
+ ngSwitchWhenDirective,
+ ngSwitchDefaultDirective,
+ ngOptionsDirective,
+ ngTranscludeDirective,
+ ngModelDirective,
+ ngListDirective,
+ ngChangeDirective,
+ requiredDirective,
+ requiredDirective,
+ ngValueDirective,
+ ngAttributeAliasDirectives,
+ ngEventDirectives,
+
+ $AnchorScrollProvider,
+ $AnimateProvider,
+ $BrowserProvider,
+ $CacheFactoryProvider,
+ $ControllerProvider,
+ $DocumentProvider,
+ $ExceptionHandlerProvider,
+ $FilterProvider,
+ $InterpolateProvider,
+ $IntervalProvider,
+ $HttpProvider,
+ $HttpBackendProvider,
+ $LocationProvider,
+ $LogProvider,
+ $ParseProvider,
+ $RootScopeProvider,
+ $QProvider,
+ $$SanitizeUriProvider,
+ $SceProvider,
+ $SceDelegateProvider,
+ $SnifferProvider,
+ $TemplateCacheProvider,
+ $TimeoutProvider,
+ $WindowProvider
+*/
+
+
/**
* @ngdoc property
* @name angular.version
@@ -1345,11 +1834,11 @@ function setupModuleLoader(window) {
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
- full: '1.1.4', // all of these placeholder strings will be replaced by grunt's
+ full: '1.2.12', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
- minor: 1,
- dot: 4,
- codeName: 'quantum-manipulation'
+ minor: 2,
+ dot: 12,
+ codeName: 'cauliflower-eradication'
};
@@ -1380,7 +1869,8 @@ function publishExternalAPI(angular){
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0},
- 'noConflict': noConflict
+ '$$minErr': minErr,
+ '$$csp': csp
});
angularModule = setupModuleLoader(window);
@@ -1392,6 +1882,10 @@ function publishExternalAPI(angular){
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
+ // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
+ $provide.provider({
+ $$sanitizeUri: $$SanitizeUriProvider
+ });
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
@@ -1403,29 +1897,27 @@ function publishExternalAPI(angular){
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
- ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
+ ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
- ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
+ ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
- ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
- ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
@@ -1434,12 +1926,14 @@ function publishExternalAPI(angular){
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
+ directive({
+ ngInclude: ngIncludeFillContentDirective
+ }).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
- $animation: $AnimationProvider,
- $animator: $AnimatorProvider,
+ $animate: $AnimateProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
@@ -1447,15 +1941,16 @@ function publishExternalAPI(angular){
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
+ $interval: $IntervalProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
- $route: $RouteProvider,
- $routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
+ $sce: $SceProvider,
+ $sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
@@ -1465,6 +1960,14 @@ function publishExternalAPI(angular){
]);
}
+/* global
+
+ -JQLitePrototype,
+ -addEventListenerFn,
+ -removeEventListenerFn,
+ -BOOLEAN_ATTR
+*/
+
//////////////////////////////////
//JQLite
//////////////////////////////////
@@ -1476,56 +1979,67 @@ function publishExternalAPI(angular){
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
- * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
- * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
- * implementation (commonly referred to as jqLite).
*
- * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
- * event fired.
+ * If jQuery is available, `angular.element` is an alias for the
+ * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
+ * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*
- * jqLite is a tiny, API-compatible subset of jQuery that allows
- * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
- * within a very small footprint, so only a subset of the jQuery API - methods, arguments and
- * invocation styles - are supported.
+ *
jqLite is a tiny, API-compatible subset of jQuery that allows
+ * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
+ * commonly needed functionality with the goal of having a very small footprint.
*
- * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
- * raw DOM references.
+ * To use jQuery, simply load it before `DOMContentLoaded` event fired.
*
- * ## Angular's jQuery lite provides the following methods:
+ *
**Note:** all element references in Angular are always wrapped with jQuery or
+ * jqLite; they are never raw DOM references.
*
- * - [addClass()](http://api.jquery.com/addClass/)
- * - [after()](http://api.jquery.com/after/)
- * - [append()](http://api.jquery.com/append/)
- * - [attr()](http://api.jquery.com/attr/)
- * - [bind()](http://api.jquery.com/bind/)
- * - [children()](http://api.jquery.com/children/)
- * - [clone()](http://api.jquery.com/clone/)
- * - [contents()](http://api.jquery.com/contents/)
- * - [css()](http://api.jquery.com/css/)
- * - [data()](http://api.jquery.com/data/)
- * - [eq()](http://api.jquery.com/eq/)
- * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name.
- * - [hasClass()](http://api.jquery.com/hasClass/)
- * - [html()](http://api.jquery.com/html/)
- * - [next()](http://api.jquery.com/next/)
- * - [parent()](http://api.jquery.com/parent/)
- * - [prepend()](http://api.jquery.com/prepend/)
- * - [prop()](http://api.jquery.com/prop/)
- * - [ready()](http://api.jquery.com/ready/)
- * - [remove()](http://api.jquery.com/remove/)
- * - [removeAttr()](http://api.jquery.com/removeAttr/)
- * - [removeClass()](http://api.jquery.com/removeClass/)
- * - [removeData()](http://api.jquery.com/removeData/)
- * - [replaceWith()](http://api.jquery.com/replaceWith/)
- * - [text()](http://api.jquery.com/text/)
- * - [toggleClass()](http://api.jquery.com/toggleClass/)
- * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Doesn't pass native event objects to handlers.
- * - [unbind()](http://api.jquery.com/unbind/)
- * - [val()](http://api.jquery.com/val/)
- * - [wrap()](http://api.jquery.com/wrap/)
+ * ## Angular's jqLite
+ * jqLite provides only the following jQuery methods:
*
- * ## In addition to the above, Angular provides additional methods to both jQuery and jQuery lite:
+ * - [`addClass()`](http://api.jquery.com/addClass/)
+ * - [`after()`](http://api.jquery.com/after/)
+ * - [`append()`](http://api.jquery.com/append/)
+ * - [`attr()`](http://api.jquery.com/attr/)
+ * - [`bind()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
+ * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
+ * - [`clone()`](http://api.jquery.com/clone/)
+ * - [`contents()`](http://api.jquery.com/contents/)
+ * - [`css()`](http://api.jquery.com/css/)
+ * - [`data()`](http://api.jquery.com/data/)
+ * - [`empty()`](http://api.jquery.com/empty/)
+ * - [`eq()`](http://api.jquery.com/eq/)
+ * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
+ * - [`hasClass()`](http://api.jquery.com/hasClass/)
+ * - [`html()`](http://api.jquery.com/html/)
+ * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
+ * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
+ * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
+ * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
+ * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
+ * - [`prepend()`](http://api.jquery.com/prepend/)
+ * - [`prop()`](http://api.jquery.com/prop/)
+ * - [`ready()`](http://api.jquery.com/ready/)
+ * - [`remove()`](http://api.jquery.com/remove/)
+ * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
+ * - [`removeClass()`](http://api.jquery.com/removeClass/)
+ * - [`removeData()`](http://api.jquery.com/removeData/)
+ * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
+ * - [`text()`](http://api.jquery.com/text/)
+ * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
+ * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
+ * - [`unbind()`](http://api.jquery.com/off/) - Does not support namespaces
+ * - [`val()`](http://api.jquery.com/val/)
+ * - [`wrap()`](http://api.jquery.com/wrap/)
*
+ * ## jQuery/jqLite Extras
+ * Angular also provides the following additional methods and events to both jQuery and jqLite:
+ *
+ * ### Events
+ * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
+ * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
+ * element before it is removed.
+ *
+ * ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
@@ -1533,6 +2047,9 @@ function publishExternalAPI(angular){
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
+ * - `isolateScope()` - retrieves an isolate {@link api/ng.$rootScope.Scope scope} if one is attached directly to the
+ * current element. This getter should be used only on elements that contain a directive which starts a new isolate
+ * scope. Calling `scope()` on this element always returns the original non-isolate scope.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
@@ -1555,6 +2072,7 @@ function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
+var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
@@ -1572,37 +2090,39 @@ function camelCase(name) {
/////////////////////////////////////////////
// jQuery mutation patch
//
-// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
+// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
-function JQLitePatchJQueryRemove(name, dispatchThis) {
+function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
- function removePatch() {
- var list = [this],
+ function removePatch(param) {
+ // jshint -W040
+ var list = filterElems && param ? [this.filter(param)] : [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
- element, childIndex, childLength, children,
- fns, events;
+ element, childIndex, childLength, children;
- while(list.length) {
- set = list.shift();
- for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
- element = jqLite(set[setIndex]);
- if (fireEvent) {
- element.triggerHandler('$destroy');
- } else {
- fireEvent = !fireEvent;
- }
- for(childIndex = 0, childLength = (children = element.children()).length;
- childIndex < childLength;
- childIndex++) {
- list.push(jQuery(children[childIndex]));
+ if (!getterIfNoArguments || param != null) {
+ while(list.length) {
+ set = list.shift();
+ for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
+ element = jqLite(set[setIndex]);
+ if (fireEvent) {
+ element.triggerHandler('$destroy');
+ } else {
+ fireEvent = !fireEvent;
+ }
+ for(childIndex = 0, childLength = (children = element.children()).length;
+ childIndex < childLength;
+ childIndex++) {
+ list.push(jQuery(children[childIndex]));
+ }
}
}
}
@@ -1615,9 +2135,12 @@ function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
+ if (isString(element)) {
+ element = trim(element);
+ }
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
- throw Error('selectors not implemented');
+ throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
@@ -1628,27 +2151,30 @@ function JQLite(element) {
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '
' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
- JQLiteAddNodes(this, div.childNodes);
- this.remove(); // detach the elements from the temporary DOM div.
+ jqLiteAddNodes(this, div.childNodes);
+ var fragment = jqLite(document.createDocumentFragment());
+ fragment.append(this); // detach the elements from the temporary DOM div.
} else {
- JQLiteAddNodes(this, element);
+ jqLiteAddNodes(this, element);
}
}
-function JQLiteClone(element) {
+function jqLiteClone(element) {
return element.cloneNode(true);
}
-function JQLiteDealoc(element){
- JQLiteRemoveData(element);
+function jqLiteDealoc(element){
+ jqLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
- JQLiteDealoc(children[i]);
+ jqLiteDealoc(children[i]);
}
}
-function JQLiteUnbind(element, type, fn) {
- var events = JQLiteExpandoStore(element, 'events'),
- handle = JQLiteExpandoStore(element, 'handle');
+function jqLiteOff(element, type, fn, unsupported) {
+ if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
+
+ var events = jqLiteExpandoStore(element, 'events'),
+ handle = jqLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
@@ -1658,30 +2184,37 @@ function JQLiteUnbind(element, type, fn) {
delete events[type];
});
} else {
- if (isUndefined(fn)) {
- removeEventListenerFn(element, type, events[type]);
- delete events[type];
- } else {
- arrayRemove(events[type], fn);
- }
+ forEach(type.split(' '), function(type) {
+ if (isUndefined(fn)) {
+ removeEventListenerFn(element, type, events[type]);
+ delete events[type];
+ } else {
+ arrayRemove(events[type] || [], fn);
+ }
+ });
}
}
-function JQLiteRemoveData(element) {
+function jqLiteRemoveData(element, name) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
+ if (name) {
+ delete jqCache[expandoId].data[name];
+ return;
+ }
+
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
- JQLiteUnbind(element);
+ jqLiteOff(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
-function JQLiteExpandoStore(element, key, value) {
+function jqLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
@@ -1696,14 +2229,14 @@ function JQLiteExpandoStore(element, key, value) {
}
}
-function JQLiteData(element, key, value) {
- var data = JQLiteExpandoStore(element, 'data'),
+function jqLiteData(element, key, value) {
+ var data = jqLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
- JQLiteExpandoStore(element, 'data', data = {});
+ jqLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
@@ -1722,34 +2255,41 @@ function JQLiteData(element, key, value) {
}
}
-function JQLiteHasClass(element, selector) {
- return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
+function jqLiteHasClass(element, selector) {
+ if (!element.getAttribute) return false;
+ return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
-function JQLiteRemoveClass(element, cssClasses) {
- if (cssClasses) {
+function jqLiteRemoveClass(element, cssClasses) {
+ if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
- element.className = trim(
- (" " + element.className + " ")
+ element.setAttribute('class', trim(
+ (" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
- .replace(" " + trim(cssClass) + " ", " ")
+ .replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
-function JQLiteAddClass(element, cssClasses) {
- if (cssClasses) {
+function jqLiteAddClass(element, cssClasses) {
+ if (cssClasses && element.setAttribute) {
+ var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
+ .replace(/[\n\t]/g, " ");
+
forEach(cssClasses.split(' '), function(cssClass) {
- if (!JQLiteHasClass(element, cssClass)) {
- element.className = trim(element.className + ' ' + trim(cssClass));
+ cssClass = trim(cssClass);
+ if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
+ existingClasses += cssClass + ' ';
}
});
+
+ element.setAttribute('class', trim(existingClasses));
}
}
-function JQLiteAddNodes(root, elements) {
+function jqLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
@@ -1760,11 +2300,11 @@ function JQLiteAddNodes(root, elements) {
}
}
-function JQLiteController(element, name) {
- return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
+function jqLiteController(element, name) {
+ return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
-function JQLiteInheritedData(element, name, value) {
+function jqLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
@@ -1772,13 +2312,26 @@ function JQLiteInheritedData(element, name, value) {
if(element[0].nodeType == 9) {
element = element.find('html');
}
+ var names = isArray(name) ? name : [name];
while (element.length) {
- if (value = element.data(name)) return value;
+
+ for (var i = 0, ii = names.length; i < ii; i++) {
+ if ((value = element.data(names[i])) !== undefined) return value;
+ }
element = element.parent();
}
}
+function jqLiteEmpty(element) {
+ for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
+ jqLiteDealoc(childNodes[i]);
+ }
+ while (element.firstChild) {
+ element.removeChild(element.firstChild);
+ }
+}
+
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
@@ -1796,9 +2349,11 @@ var JQLitePrototype = JQLite.prototype = {
if (document.readyState === 'complete'){
setTimeout(trigger);
} else {
- this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
+ this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
- JQLite(window).bind('load', trigger); // fallback to window.onload for others
+ // jshint -W064
+ JQLite(window).on('load', trigger); // fallback to window.onload for others
+ // jshint +W064
}
},
toString: function() {
@@ -1840,24 +2395,30 @@ function getBooleanAttrName(element, name) {
}
forEach({
- data: JQLiteData,
- inheritedData: JQLiteInheritedData,
+ data: jqLiteData,
+ inheritedData: jqLiteInheritedData,
scope: function(element) {
- return JQLiteInheritedData(element, '$scope');
+ // Can't use jqLiteData here directly so we stay compatible with jQuery!
+ return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
- controller: JQLiteController ,
+ isolateScope: function(element) {
+ // Can't use jqLiteData here directly so we stay compatible with jQuery!
+ return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
+ },
+
+ controller: jqLiteController ,
injector: function(element) {
- return JQLiteInheritedData(element, '$injector');
+ return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
- hasClass: JQLiteHasClass,
+ hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
@@ -1920,27 +2481,38 @@ forEach({
}
},
- text: extend((msie < 9)
- ? function(element, value) {
- if (element.nodeType == 1 /** Element */) {
- if (isUndefined(value))
- return element.innerText;
- element.innerText = value;
- } else {
- if (isUndefined(value))
- return element.nodeValue;
- element.nodeValue = value;
- }
+ text: (function() {
+ var NODE_TYPE_TEXT_PROPERTY = [];
+ if (msie < 9) {
+ NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
+ NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
+ } else {
+ NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
+ NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
+ }
+ getText.$dv = '';
+ return getText;
+
+ function getText(element, value) {
+ var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
+ if (isUndefined(value)) {
+ return textProp ? element[textProp] : '';
}
- : function(element, value) {
- if (isUndefined(value)) {
- return element.textContent;
- }
- element.textContent = value;
- }, {$dv:''}),
+ element[textProp] = value;
+ }
+ })(),
val: function(element, value) {
if (isUndefined(value)) {
+ if (nodeName_(element) === 'SELECT' && element.multiple) {
+ var result = [];
+ forEach(element.options, function (option) {
+ if (option.selected) {
+ result.push(option.value || option.text);
+ }
+ });
+ return result.length === 0 ? null : result;
+ }
return element.value;
}
element.value = value;
@@ -1951,10 +2523,12 @@ forEach({
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
- JQLiteDealoc(childNodes[i]);
+ jqLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
- }
+ },
+
+ empty: jqLiteEmpty
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
@@ -1962,14 +2536,16 @@ forEach({
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
- // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
+ // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
- if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
+ // jqLiteEmpty takes no arguments but is a setter.
+ if (fn !== jqLiteEmpty &&
+ (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
- for(i=0; i < this.length; i++) {
- if (fn === JQLiteData) {
+ for (i = 0; i < this.length; i++) {
+ if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
@@ -1982,18 +2558,23 @@ forEach({
return this;
} else {
// we are a read, so read the first child.
- if (this.length)
- return fn(this[0], arg1, arg2);
+ var value = fn.$dv;
+ // Only if we have $dv do we iterate over all, otherwise it is just the first element.
+ var jj = (value === undefined) ? Math.min(this.length, 1) : this.length;
+ for (var j = 0; j < jj; j++) {
+ var nodeValue = fn(this[j], arg1, arg2);
+ value = value ? value + nodeValue : nodeValue;
+ }
+ return value;
}
} else {
// we are a write, so apply to all children
- for(i=0; i < this.length; i++) {
+ for (i = 0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
- return fn.$dv;
};
});
@@ -2025,10 +2606,13 @@ function createEventHandler(element, events) {
}
event.isDefaultPrevented = function() {
- return event.defaultPrevented;
+ return event.defaultPrevented || event.returnValue === false;
};
- forEach(events[type || event.type], function(fn) {
+ // Copy event handlers in case event handlers array is modified during execution.
+ var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
+
+ forEach(eventHandlersCopy, function(fn) {
fn.call(element, event);
});
@@ -2056,54 +2640,90 @@ function createEventHandler(element, events) {
// selector.
//////////////////////////////////////////
forEach({
- removeData: JQLiteRemoveData,
+ removeData: jqLiteRemoveData,
- dealoc: JQLiteDealoc,
+ dealoc: jqLiteDealoc,
- bind: function bindFn(element, type, fn){
- var events = JQLiteExpandoStore(element, 'events'),
- handle = JQLiteExpandoStore(element, 'handle');
+ on: function onFn(element, type, fn, unsupported){
+ if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
- if (!events) JQLiteExpandoStore(element, 'events', events = {});
- if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
+ var events = jqLiteExpandoStore(element, 'events'),
+ handle = jqLiteExpandoStore(element, 'handle');
+
+ if (!events) jqLiteExpandoStore(element, 'events', events = {});
+ if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
- var counter = 0;
+ var contains = document.body.contains || document.body.compareDocumentPosition ?
+ function( a, b ) {
+ // jshint bitwise: false
+ var adown = a.nodeType === 9 ? a.documentElement : a,
+ bup = b && b.parentNode;
+ return a === bup || !!( bup && bup.nodeType === 1 && (
+ adown.contains ?
+ adown.contains( bup ) :
+ a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
+ ));
+ } :
+ function( a, b ) {
+ if ( b ) {
+ while ( (b = b.parentNode) ) {
+ if ( b === a ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
- events.mouseenter = [];
- events.mouseleave = [];
+ events[type] = [];
- bindFn(element, 'mouseover', function(event) {
- counter++;
- if (counter == 1) {
- handle(event, 'mouseenter');
- }
- });
- bindFn(element, 'mouseout', function(event) {
- counter --;
- if (counter == 0) {
- handle(event, 'mouseleave');
+ // Refer to jQuery's implementation of mouseenter & mouseleave
+ // Read about mouseenter and mouseleave:
+ // http://www.quirksmode.org/js/events_mouse.html#link8
+ var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
+
+ onFn(element, eventmap[type], function(event) {
+ var target = this, related = event.relatedTarget;
+ // For mousenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if ( !related || (related !== target && !contains(target, related)) ){
+ handle(event, type);
}
});
+
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
- eventFns = events[type]
+ eventFns = events[type];
}
eventFns.push(fn);
});
},
- unbind: JQLiteUnbind,
+ off: jqLiteOff,
+
+ one: function(element, type, fn) {
+ element = jqLite(element);
+
+ //add the listener twice so that when it is called
+ //you can remove the original function and still be
+ //able to call element.off(ev, fn) normally
+ element.on(type, function onFn() {
+ element.off(type, fn);
+ element.off(type, onFn);
+ });
+ element.on(type, fn);
+ },
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
- JQLiteDealoc(element);
+ jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
@@ -2139,12 +2759,7 @@ forEach({
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
- if (index) {
- element.insertBefore(child, index);
- } else {
- element.appendChild(child);
- index = child;
- }
+ element.insertBefore(child, index);
});
}
},
@@ -2159,7 +2774,7 @@ forEach({
},
remove: function(element) {
- JQLiteDealoc(element);
+ jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
@@ -2172,14 +2787,14 @@ forEach({
});
},
- addClass: JQLiteAddClass,
- removeClass: JQLiteRemoveClass,
+ addClass: jqLiteAddClass,
+ removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
- condition = !JQLiteHasClass(element, selector);
+ condition = !jqLiteHasClass(element, selector);
}
- (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
+ (condition ? jqLiteAddClass : jqLiteRemoveClass)(element, selector);
},
parent: function(element) {
@@ -2201,37 +2816,52 @@ forEach({
},
find: function(element, selector) {
- return element.getElementsByTagName(selector);
+ if (element.getElementsByTagName) {
+ return element.getElementsByTagName(selector);
+ } else {
+ return [];
+ }
},
- clone: JQLiteClone,
+ clone: jqLiteClone,
- triggerHandler: function(element, eventName) {
- var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName];
+ triggerHandler: function(element, eventName, eventData) {
+ var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
+
+ eventData = eventData || [];
+
+ var event = [{
+ preventDefault: noop,
+ stopPropagation: noop
+ }];
forEach(eventFns, function(fn) {
- fn.call(element, null);
+ fn.apply(element, event.concat(eventData));
});
}
}, function(fn, name){
/**
* chaining functions
*/
- JQLite.prototype[name] = function(arg1, arg2) {
+ JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for(var i=0; i < this.length; i++) {
- if (value == undefined) {
- value = fn(this[i], arg1, arg2);
- if (value !== undefined) {
+ if (isUndefined(value)) {
+ value = fn(this[i], arg1, arg2, arg3);
+ if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
- JQLiteAddNodes(value, fn(this[i], arg1, arg2));
+ jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
- return value == undefined ? this : value;
+ return isDefined(value) ? value : this;
};
+
+ // bind legacy bind/unbind to on/off
+ JQLite.prototype.bind = JQLite.prototype.on;
+ JQLite.prototype.unbind = JQLite.prototype.off;
});
/**
@@ -2326,6 +2956,28 @@ HashMap.prototype = {
* $rootScope.$digest();
* });
*
+ *
+ * Sometimes you want to get access to the injector of a currently running Angular app
+ * from outside Angular. Perhaps, you want to inject and compile some markup after the
+ * application has been bootstrapped. You can do this using extra `injector()` added
+ * to JQuery/jqLite elements. See {@link angular.element}.
+ *
+ * *This is fairly rare but could be the case if a third party library is injecting the
+ * markup.*
+ *
+ * In the following example a new block of HTML containing a `ng-controller`
+ * directive is added to the end of the document body by JQuery. We then compile and link
+ * it into the current AngularJS scope.
+ *
+ *
*/
@@ -2341,6 +2993,7 @@ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
+var $injectorMinErr = minErr('$injector');
function annotate(fn) {
var $inject,
fnText,
@@ -2350,18 +3003,20 @@ function annotate(fn) {
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
- fnText = fn.toString().replace(STRIP_COMMENTS, '');
- argDecl = fnText.match(FN_ARGS);
- forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
- arg.replace(FN_ARG, function(all, underscore, name){
- $inject.push(name);
+ if (fn.length) {
+ fnText = fn.toString().replace(STRIP_COMMENTS, '');
+ argDecl = fnText.match(FN_ARGS);
+ forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
+ arg.replace(FN_ARG, function(all, underscore, name){
+ $inject.push(name);
+ });
});
- });
+ }
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
- assertArgFn(fn[last], 'fn')
+ assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
@@ -2395,7 +3050,7 @@ function annotate(fn) {
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
- * following ways are all valid way of annotating function with injection arguments and are equivalent.
+ * following are all valid ways of annotating function with injection arguments and are equivalent.
*
*
* // inferred (only works if code not minified/obfuscated)
@@ -2412,9 +3067,9 @@ function annotate(fn) {
*
* ## Inference
*
- * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
- * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
- * tools since these tools change the argument names.
+ * In JavaScript calling `toString()` on a function returns the function definition. The definition
+ * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
+ * minification, and obfuscation tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
@@ -2443,24 +3098,38 @@ function annotate(fn) {
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
- * @param {!function} fn The function to invoke. The function arguments come form the function annotation.
+ * @param {!function} fn The function to invoke. Function parameters are injected according to the
+ * {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
- * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
- * the `$injector` is consulted.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this
+ * object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
+/**
+ * @ngdoc method
+ * @name AUTO.$injector#has
+ * @methodOf AUTO.$injector
+ *
+ * @description
+ * Allows the user to query if the particular service exist.
+ *
+ * @param {string} Name of the service to query.
+ * @returns {boolean} returns true if injector has given service.
+ */
+
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
- * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
- * all of the arguments to the constructor function as specified by the constructor annotation.
+ * Create a new instance of JS type. The method takes a constructor function invokes the new
+ * operator and supplies all of the arguments to the constructor function as specified by the
+ * constructor annotation.
*
* @param {function} Type Annotated constructor function.
- * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
- * the `$injector` is consulted.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this
+ * object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
@@ -2470,14 +3139,16 @@ function annotate(fn) {
* @methodOf AUTO.$injector
*
* @description
- * Returns an array of service names which the function is requesting for injection. This API is used by the injector
- * to determine which services need to be injected into the function when the function is invoked. There are three
- * ways in which the function can be annotated with the needed dependencies.
+ * Returns an array of service names which the function is requesting for injection. This API is
+ * used by the injector to determine which services need to be injected into the function when the
+ * function is invoked. There are three ways in which the function can be annotated with the needed
+ * dependencies.
*
* # Argument names
*
- * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
- * the function into a string using `toString()` method and extracting the argument names.
+ * The simplest form is to extract the dependencies from the arguments of the function. This is done
+ * by converting the function into a string using `toString()` method and extracting the argument
+ * names.
*
* // Given
* function MyController($scope, $route) {
@@ -2488,20 +3159,20 @@ function annotate(fn) {
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
*
*
- * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
- * are supported.
+ * This method does not work with code minification / obfuscation. For this reason the following
+ * annotation strategies are supported.
*
* # The `$inject` property
*
- * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
- * services to be injected into the function.
+ * If a function has an `$inject` property and its value is an array of strings, then the strings
+ * represent names of services to be injected into the function.
*
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
- * MyController.$inject = ['$scope', '$route'];
+ * MyController['$inject'] = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
@@ -2509,9 +3180,9 @@ function annotate(fn) {
*
* # The array notation
*
- * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
- * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
- * minification is a better choice:
+ * It is often desirable to inline Injected functions and that's when setting the `$inject` property
+ * is very inconvenient. In these situations using the array notation to specify the dependencies in
+ * a way that survives minification is a better choice:
*
*
* // We wish to write this (not minification / obfuscation safe)
@@ -2524,7 +3195,7 @@ function annotate(fn) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
- * injector.invoke(tempFn);
+ * injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
@@ -2537,8 +3208,8 @@ function annotate(fn) {
* ).toEqual(['$compile', '$rootScope']);
*
*
- * @param {function|Array.} fn Function for which dependent service names need to be retrieved as described
- * above.
+ * @param {function|Array.} fn Function for which dependent service names need to
+ * be retrieved as described above.
*
* @returns {Array.} The names of the services which the function requires.
*/
@@ -2552,48 +3223,38 @@ function annotate(fn) {
*
* @description
*
- * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
- * The providers share the same name as the instance they create with `Provider` suffixed to them.
+ * The {@link AUTO.$provide $provide} service has a number of methods for registering components
+ * with the {@link AUTO.$injector $injector}. Many of these functions are also exposed on
+ * {@link angular.Module}.
*
- * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
- * a service. The Provider can have additional methods which would allow for configuration of the provider.
+ * An Angular **service** is a singleton object created by a **service factory**. These **service
+ * factories** are functions which, in turn, are created by a **service provider**.
+ * The **service providers** are constructor functions. When instantiated they must contain a
+ * property called `$get`, which holds the **service factory** function.
*
- *
- * function GreetProvider() {
- * var salutation = 'Hello';
+ * When you request a service, the {@link AUTO.$injector $injector} is responsible for finding the
+ * correct **service provider**, instantiating it and then calling its `$get` **service factory**
+ * function to get the instance of the **service**.
*
- * this.salutation = function(text) {
- * salutation = text;
- * };
+ * Often services have no configuration options and there is no need to add methods to the service
+ * provider. The provider will be no more than a constructor function with a `$get` property. For
+ * these cases the {@link AUTO.$provide $provide} service has additional helper methods to register
+ * services without specifying a provider.
*
- * this.$get = function() {
- * return function (name) {
- * return salutation + ' ' + name + '!';
- * };
- * };
- * }
+ * * {@link AUTO.$provide#methods_provider provider(provider)} - registers a **service provider** with the
+ * {@link AUTO.$injector $injector}
+ * * {@link AUTO.$provide#methods_constant constant(obj)} - registers a value/object that can be accessed by
+ * providers and services.
+ * * {@link AUTO.$provide#methods_value value(obj)} - registers a value/object that can only be accessed by
+ * services, not providers.
+ * * {@link AUTO.$provide#methods_factory factory(fn)} - registers a service **factory function**, `fn`,
+ * that will be wrapped in a **service provider** object, whose `$get` property will contain the
+ * given factory function.
+ * * {@link AUTO.$provide#methods_service service(class)} - registers a **constructor function**, `class` that
+ * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
+ * a new object using the given constructor function.
*
- * describe('Greeter', function(){
- *
- * beforeEach(module(function($provide) {
- * $provide.provider('greet', GreetProvider);
- * });
- *
- * it('should greet', inject(function(greet) {
- * expect(greet('angular')).toEqual('Hello angular!');
- * }));
- *
- * it('should allow configuration of salutation', function() {
- * module(function(greetProvider) {
- * greetProvider.salutation('Ahoj');
- * });
- * inject(function(greet) {
- * expect(greet('angular')).toEqual('Ahoj angular!');
- * });
- * )};
- *
- * });
- *
+ * See the individual methods for more information and examples.
*/
/**
@@ -2602,17 +3263,95 @@ function annotate(fn) {
* @methodOf AUTO.$provide
* @description
*
- * Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
+ * Register a **provider function** with the {@link AUTO.$injector $injector}. Provider functions
+ * are constructor functions, whose instances are responsible for "providing" a factory for a
+ * service.
*
- * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
+ * Service provider names start with the name of the service they provide followed by `Provider`.
+ * For example, the {@link ng.$log $log} service has a provider called
+ * {@link ng.$logProvider $logProvider}.
+ *
+ * Service provider objects can have additional methods which allow configuration of the provider
+ * and its service. Importantly, you can configure what kind of service is created by the `$get`
+ * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
+ * method {@link ng.$logProvider#debugEnabled debugEnabled}
+ * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
+ * console or not.
+ *
+ * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
+ 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
- * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
- * - `Constructor`: a new instance of the provider will be created using
- * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
+ * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
+ * - `Constructor`: a new instance of the provider will be created using
+ * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
+
+ * @example
+ *
+ * The following example shows how to create a simple event tracking service and register it using
+ * {@link AUTO.$provide#methods_provider $provide.provider()}.
+ *
+ *
+ * // Define the eventTracker provider
+ * function EventTrackerProvider() {
+ * var trackingUrl = '/track';
+ *
+ * // A provider method for configuring where the tracked events should been saved
+ * this.setTrackingUrl = function(url) {
+ * trackingUrl = url;
+ * };
+ *
+ * // The service factory function
+ * this.$get = ['$http', function($http) {
+ * var trackedEvents = {};
+ * return {
+ * // Call this to track an event
+ * event: function(event) {
+ * var count = trackedEvents[event] || 0;
+ * count += 1;
+ * trackedEvents[event] = count;
+ * return count;
+ * },
+ * // Call this to save the tracked events to the trackingUrl
+ * save: function() {
+ * $http.post(trackingUrl, trackedEvents);
+ * }
+ * };
+ * }];
+ * }
+ *
+ * describe('eventTracker', function() {
+ * var postSpy;
+ *
+ * beforeEach(module(function($provide) {
+ * // Register the eventTracker provider
+ * $provide.provider('eventTracker', EventTrackerProvider);
+ * }));
+ *
+ * beforeEach(module(function(eventTrackerProvider) {
+ * // Configure eventTracker provider
+ * eventTrackerProvider.setTrackingUrl('/custom-track');
+ * }));
+ *
+ * it('tracks events', inject(function(eventTracker) {
+ * expect(eventTracker.event('login')).toEqual(1);
+ * expect(eventTracker.event('login')).toEqual(2);
+ * }));
+ *
+ * it('saves to the tracking url', inject(function(eventTracker, $http) {
+ * postSpy = spyOn($http, 'post');
+ * eventTracker.event('login');
+ * eventTracker.save();
+ * expect(postSpy).toHaveBeenCalled();
+ * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
+ * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
+ * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
+ * }));
+ * });
+ *
*/
/**
@@ -2621,12 +3360,32 @@ function annotate(fn) {
* @methodOf AUTO.$provide
* @description
*
- * A short hand for configuring services if only `$get` method is required.
+ * Register a **service factory**, which will be called to return the service instance.
+ * This is short for registering a service where its provider consists of only a `$get` property,
+ * which is the given service factory function.
+ * You should use {@link AUTO.$provide#factory $provide.factory(getFn)} if you do not need to
+ * configure your service in a provider.
*
* @param {string} name The name of the instance.
- * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
- * `$provide.provider(name, {$get: $getFn})`.
+ * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
+ * for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
+ *
+ * @example
+ * Here is an example of registering a service
+ *
*/
@@ -2636,11 +3395,39 @@ function annotate(fn) {
* @methodOf AUTO.$provide
* @description
*
- * A short hand for registering service of given class.
+ * Register a **service constructor**, which will be invoked with `new` to create the service
+ * instance.
+ * This is short for registering a service where its provider's `$get` property is the service
+ * constructor function that will be used to instantiate the service instance.
+ *
+ * You should use {@link AUTO.$provide#methods_service $provide.service(class)} if you define your service
+ * as a type/class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
+ *
+ * @example
+ * Here is an example of registering a service using
+ * {@link AUTO.$provide#methods_service $provide.service(class)}.
+ *
*/
@@ -2650,11 +3437,31 @@ function annotate(fn) {
* @methodOf AUTO.$provide
* @description
*
- * A short hand for configuring services if the `$get` method is a constant.
+ * Register a **value service** with the {@link AUTO.$injector $injector}, such as a string, a
+ * number, an array, an object or a function. This is short for registering a service where its
+ * provider's `$get` property is a factory function that takes no arguments and returns the **value
+ * service**.
+ *
+ * Value services are similar to constant services, except that they cannot be injected into a
+ * module configuration function (see {@link angular.Module#config}) but they can be overridden by
+ * an Angular
+ * {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
+ *
+ * @example
+ * Here are some examples of creating value services.
+ *
*/
@@ -2664,13 +3471,26 @@ function annotate(fn) {
* @methodOf AUTO.$provide
* @description
*
- * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
- * into configuration function (other modules) and it is not interceptable by
- * {@link AUTO.$provide#decorator decorator}.
+ * Register a **constant service**, such as a string, a number, an array, an object or a function,
+ * with the {@link AUTO.$injector $injector}. Unlike {@link AUTO.$provide#value value} it can be
+ * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
+ * be overridden by an Angular {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
+ *
+ * @example
+ * Here a some examples of creating constants:
+ *
*/
@@ -2680,17 +3500,29 @@ function annotate(fn) {
* @methodOf AUTO.$provide
* @description
*
- * Decoration of service, allows the decorator to intercept the service instance creation. The
- * returned instance may be the original instance, or a new instance which delegates to the
- * original instance.
+ * Register a **service decorator** with the {@link AUTO.$injector $injector}. A service decorator
+ * intercepts the creation of a service, allowing it to override or modify the behaviour of the
+ * service. The object returned by the decorator may be the original service, or a new service
+ * object which replaces or wraps and delegates to the original service.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
- * instanciated. The function is called using the {@link AUTO.$injector#invoke
- * injector.invoke} method and is therefore fully injectable. Local injection arguments:
+ * instantiated and should return the decorated service instance. The function is called using
+ * the {@link AUTO.$injector#invoke injector.invoke} method and is therefore fully injectable.
+ * Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
+ *
+ * @example
+ * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
+ * calls to {@link ng.$log#error $log.warn()}.
+ *
+
+
+ function ScrollCtrl($scope, $location, $anchorScroll) {
+ $scope.gotoBottom = function (){
+ // set the location.hash to the id of
+ // the element you wish to scroll to.
+ $location.hash('bottom');
+
+ // call $anchorScroll()
+ $anchorScroll();
+ }
+ }
+
+
+ #scrollArea {
+ height: 350px;
+ overflow: auto;
+ }
+
+ #bottom {
+ display: block;
+ margin-top: 2000px;
+ }
+
+
*/
function $AnchorScrollProvider() {
@@ -2968,382 +3835,232 @@ function $AnchorScrollProvider() {
}];
}
+var $animateMinErr = minErr('$animate');
/**
* @ngdoc object
- * @name ng.$animationProvider
+ * @name ng.$animateProvider
+ *
* @description
+ * Default implementation of $animate that doesn't perform any animations, instead just
+ * synchronously performs DOM
+ * updates and calls done() callbacks.
*
- * The $AnimationProvider provider allows developers to register and access custom JavaScript animations directly inside
- * of a module.
+ * In order to enable animations the ngAnimate module has to be loaded.
*
+ * To see the functional implementation check out src/ngAnimate/animate.js
*/
-$AnimationProvider.$inject = ['$provide'];
-function $AnimationProvider($provide) {
- var suffix = 'Animation';
+var $AnimateProvider = ['$provide', function($provide) {
+
+
+ this.$$selectors = {};
+
/**
* @ngdoc function
- * @name ng.$animation#register
- * @methodOf ng.$animationProvider
+ * @name ng.$animateProvider#register
+ * @methodOf ng.$animateProvider
*
* @description
- * Registers a new injectable animation factory function. The factory function produces the animation object which
- * has these two properties:
+ * Registers a new injectable animation factory function. The factory function produces the
+ * animation object which contains callback functions for each event that is expected to be
+ * animated.
*
- * * `setup`: `function(Element):*` A function which receives the starting state of the element. The purpose
- * of this function is to get the element ready for animation. Optionally the function returns an memento which
- * is passed to the `start` function.
- * * `start`: `function(Element, doneFunction, *)` The element to animate, the `doneFunction` to be called on
- * element animation completion, and an optional memento from the `setup` function.
+ * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
+ * must be called once the element animation is complete. If a function is returned then the
+ * animation service will use this function to cancel the animation whenever a cancel event is
+ * triggered.
+ *
+ *
+ *
+ * return {
+ * eventFn : function(element, done) {
+ * //code to run the animation
+ * //once complete, then run done()
+ * return function cancellationFunction() {
+ * //code to cancel the animation
+ * }
+ * }
+ * }
+ *
*
* @param {string} name The name of the animation.
- * @param {function} factory The factory function that will be executed to return the animation object.
- *
+ * @param {function} factory The factory function that will be executed to return the animation
+ * object.
*/
this.register = function(name, factory) {
- $provide.factory(camelCase(name) + suffix, factory);
+ var key = name + '-animation';
+ if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
+ "Expecting class selector starting with '.' got '{0}'.", name);
+ this.$$selectors[name.substr(1)] = key;
+ $provide.factory(key, factory);
};
- this.$get = ['$injector', function($injector) {
+ /**
+ * @ngdoc function
+ * @name ng.$animateProvider#classNameFilter
+ * @methodOf ng.$animateProvider
+ *
+ * @description
+ * Sets and/or returns the CSS class regular expression that is checked when performing
+ * an animation. Upon bootstrap the classNameFilter value is not set at all and will
+ * therefore enable $animate to attempt to perform an animation on any element.
+ * When setting the classNameFilter value, animations will only be performed on elements
+ * that successfully match the filter expression. This in turn can boost performance
+ * for low-powered devices as well as applications containing a lot of structural operations.
+ * @param {RegExp=} expression The className expression which will be checked against all animations
+ * @return {RegExp} The current CSS className expression value. If null then there is no expression value
+ */
+ this.classNameFilter = function(expression) {
+ if(arguments.length === 1) {
+ this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
+ }
+ return this.$$classNameFilter;
+ };
+
+ this.$get = ['$timeout', function($timeout) {
+
/**
- * @ngdoc function
- * @name ng.$animation
- * @function
*
- * @description
- * The $animation service is used to retrieve any defined animation functions. When executed, the $animation service
- * will return a object that contains the setup and start functions that were defined for the animation.
+ * @ngdoc object
+ * @name ng.$animate
+ * @description The $animate service provides rudimentary DOM manipulation functions to
+ * insert, remove and move elements within the DOM, as well as adding and removing classes.
+ * This service is the core service used by the ngAnimate $animator service which provides
+ * high-level animation hooks for CSS and JavaScript.
*
- * @param {String} name Name of the animation function to retrieve. Animation functions are registered and stored
- * inside of the AngularJS DI so a call to $animate('custom') is the same as injecting `customAnimation`
- * via dependency injection.
- * @return {Object} the animation object which contains the `setup` and `start` functions that perform the animation.
+ * $animate is available in the AngularJS core, however, the ngAnimate module must be included
+ * to enable full out animation support. Otherwise, $animate will only perform simple DOM
+ * manipulation operations.
+ *
+ * To learn more about enabling animation support, click here to visit the {@link ngAnimate
+ * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
+ * page}.
*/
- return function $animation(name) {
- if (name) {
- try {
- return $injector.get(camelCase(name) + suffix);
- } catch (e) {
- //TODO(misko): this is a hack! we should have a better way to test if the injector has a given key.
- // The issue is that the animations are optional, and if not present they should be silently ignored.
- // The proper way to fix this is to add API onto the injector so that we can ask to see if a given
- // animation is supported.
- }
- }
- }
- }];
-};
-
-// NOTE: this is a pseudo directive.
-
-/**
- * @ngdoc directive
- * @name ng.directive:ngAnimate
- *
- * @description
- * The `ngAnimate` directive works as an attribute that is attached alongside pre-existing directives.
- * It effects how the directive will perform DOM manipulation. This allows for complex animations to take place while
- * without burduning the directive which uses the animation with animation details. The built dn directives
- * `ngRepeat`, `ngInclude`, `ngSwitch`, `ngShow`, `ngHide` and `ngView` already accept `ngAnimate` directive.
- * Custom directives can take advantage of animation through {@link ng.$animator $animator service}.
- *
- * Below is a more detailed breakdown of the supported callback events provided by pre-exisitng ng directives:
- *
- * * {@link ng.directive:ngRepeat#animations ngRepeat} — enter, leave and move
- * * {@link ng.directive:ngView#animations ngView} — enter and leave
- * * {@link ng.directive:ngInclude#animations ngInclude} — enter and leave
- * * {@link ng.directive:ngSwitch#animations ngSwitch} — enter and leave
- * * {@link ng.directive:ngShow#animations ngShow & ngHide} - show and hide respectively
- *
- * You can find out more information about animations upon visiting each directive page.
- *
- * Below is an example of a directive that makes use of the ngAnimate attribute:
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- * The `event1` and `event2` attributes refer to the animation events specific to the directive that has been assigned.
- *
- *
CSS-defined Animations
- * By default, ngAnimate attaches two CSS3 classes per animation event to the DOM element to achieve the animation.
- * This is up to you, the developer, to ensure that the animations take place using cross-browser CSS3 transitions.
- * All that is required is the following CSS code:
- *
- *
- *
- *
- *
- *
- *
- * Upon DOM mutation, the setup class is added first, then the browser is allowed to reflow the content and then,
- * the start class is added to trigger the animation. The ngAnimate directive will automatically extract the duration
- * of the animation to determine when the animation ends. Once the animation is over then both CSS classes will be
- * removed from the DOM. If a browser does not support CSS transitions then the animation will start and end
- * immediately resulting in a DOM element that is at it's final state. This final state is when the DOM element
- * has no CSS animation classes surrounding it.
- *
- *
JavaScript-defined Animations
- * In the event that you do not want to use CSS3 animations or if you wish to offer animations to browsers that do not
- * yet support them, then you can make use of JavaScript animations defined inside ngModule.
- *
- *
- * var ngModule = angular.module('YourApp', []);
- * ngModule.animation('animate-enter', function() {
- * return {
- * setup : function(element) {
- * //prepare the element for animation
- * element.css({ 'opacity': 0 });
- * var memo = "..."; //this value is passed to the start function
- * return memo;
- * },
- * start : function(element, done, memo) {
- * //start the animation
- * element.animate({
- * 'opacity' : 1
- * }, function() {
- * //call when the animation is complete
- * done()
- * });
- * }
- * }
- * });
- *
- *
- * As you can see, the JavaScript code follows a similar template to the CSS3 animations. Once defined, the animation
- * can be used in the same way with the ngAnimate attribute. Keep in mind that, when using JavaScript-enabled
- * animations, ngAnimate will also add in the same CSS classes that CSS-enabled animations do (even if you're using
- * JavaScript animations) to animated the element, but it will not attempt to find any CSS3 transition duration value.
- * It will instead close off the animation once the provided done function is executed. So it's important that you
- * make sure your animations remember to fire off the done function once the animations are complete.
- *
- * @param {expression} ngAnimate Used to configure the DOM manipulation animations.
- *
- */
-
-/**
- * @ngdoc function
- * @name ng.$animator
- *
- * @description
- * The $animator service provides the DOM manipulation API which is decorated with animations.
- *
- * @param {Scope} scope the scope for the ng-animate.
- * @param {Attributes} attr the attributes object which contains the ngAnimate key / value pair. (The attributes are
- * passed into the linking function of the directive using the `$animator`.)
- * @return {object} the animator object which contains the enter, leave, move, show, hide and animate methods.
- */
-var $AnimatorProvider = function() {
- this.$get = ['$animation', '$window', '$sniffer', function($animation, $window, $sniffer) {
- return function(scope, attrs) {
- var ngAnimateAttr = attrs.ngAnimate;
- var animator = {};
+ return {
/**
+ *
* @ngdoc function
- * @name ng.animator#enter
- * @methodOf ng.$animator
+ * @name ng.$animate#enter
+ * @methodOf ng.$animate
* @function
- *
- * @description
- * Injects the element object into the DOM (inside of the parent element) and then runs the enter animation.
- *
- * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation
- * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation
- * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation
- */
- animator.enter = animateActionFactory('enter', insert, noop);
-
- /**
- * @ngdoc function
- * @name ng.animator#leave
- * @methodOf ng.$animator
- * @function
- *
- * @description
- * Runs the leave animation operation and, upon completion, removes the element from the DOM.
- *
- * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation
- * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the leave animation
- */
- animator.leave = animateActionFactory('leave', noop, remove);
-
- /**
- * @ngdoc function
- * @name ng.animator#move
- * @methodOf ng.$animator
- * @function
- *
- * @description
- * Fires the move DOM operation. Just before the animation starts, the animator will either append it into the parent container or
- * add the element directly after the after element if present. Then the move animation will be run.
- *
- * @param {jQuery/jqLite element} element the element that will be the focus of the move animation
- * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation
- * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation
- */
- animator.move = animateActionFactory('move', move, noop);
-
- /**
- * @ngdoc function
- * @name ng.animator#show
- * @methodOf ng.$animator
- * @function
- *
- * @description
- * Reveals the element by setting the CSS property `display` to `block` and then starts the show animation directly after.
- *
- * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden
- */
- animator.show = animateActionFactory('show', show, noop);
-
- /**
- * @ngdoc function
- * @name ng.animator#hide
- * @methodOf ng.$animator
- *
- * @description
- * Starts the hide animation first and sets the CSS `display` property to `none` upon completion.
- *
- * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden
- */
- animator.hide = animateActionFactory('hide', noop, hide);
- return animator;
-
- function animateActionFactory(type, beforeFn, afterFn) {
- var ngAnimateValue = ngAnimateAttr && scope.$eval(ngAnimateAttr);
- var className = ngAnimateAttr
- ? isObject(ngAnimateValue) ? ngAnimateValue[type] : ngAnimateValue + '-' + type
- : '';
- var animationPolyfill = $animation(className);
-
- var polyfillSetup = animationPolyfill && animationPolyfill.setup;
- var polyfillStart = animationPolyfill && animationPolyfill.start;
-
- if (!className) {
- return function(element, parent, after) {
- beforeFn(element, parent, after);
- afterFn(element, parent, after);
- }
+ * @description Inserts the element into the DOM either after the `after` element or within
+ * the `parent` element. Once complete, the done() callback will be fired (if provided).
+ * @param {jQuery/jqLite element} element the element which will be inserted into the DOM
+ * @param {jQuery/jqLite element} parent the parent element which will append the element as
+ * a child (if the after element is not present)
+ * @param {jQuery/jqLite element} after the sibling element which will append the element
+ * after itself
+ * @param {function=} done callback function that will be called after the element has been
+ * inserted into the DOM
+ */
+ enter : function(element, parent, after, done) {
+ if (after) {
+ after.after(element);
} else {
- var setupClass = className + '-setup';
- var startClass = className + '-start';
-
- return function(element, parent, after) {
- if (!$sniffer.supportsTransitions && !polyfillSetup && !polyfillStart) {
- beforeFn(element, parent, after);
- afterFn(element, parent, after);
- return;
- }
-
- element.addClass(setupClass);
- beforeFn(element, parent, after);
- if (element.length == 0) return done();
-
- var memento = (polyfillSetup || noop)(element);
-
- // $window.setTimeout(beginAnimation, 0); this was causing the element not to animate
- // keep at 1 for animation dom rerender
- $window.setTimeout(beginAnimation, 1);
-
- function beginAnimation() {
- element.addClass(startClass);
- if (polyfillStart) {
- polyfillStart(element, done, memento);
- } else if (isFunction($window.getComputedStyle)) {
- var vendorTransitionProp = $sniffer.vendorPrefix + 'Transition';
- var w3cTransitionProp = 'transition'; //one day all browsers will have this
-
- var durationKey = 'Duration';
- var duration = 0;
- //we want all the styles defined before and after
- forEach(element, function(element) {
- var globalStyles = $window.getComputedStyle(element) || {};
- duration = Math.max(
- parseFloat(globalStyles[w3cTransitionProp + durationKey]) ||
- parseFloat(globalStyles[vendorTransitionProp + durationKey]) ||
- 0,
- duration);
- });
-
- $window.setTimeout(done, duration * 1000);
- } else {
- done();
- }
- }
-
- function done() {
- afterFn(element, parent, after);
- element.removeClass(setupClass);
- element.removeClass(startClass);
- }
+ if (!parent || !parent[0]) {
+ parent = after.parent();
}
+ parent.append(element);
}
- }
- }
+ done && $timeout(done, 0, false);
+ },
- function show(element) {
- element.css('display', '');
- }
+ /**
+ *
+ * @ngdoc function
+ * @name ng.$animate#leave
+ * @methodOf ng.$animate
+ * @function
+ * @description Removes the element from the DOM. Once complete, the done() callback will be
+ * fired (if provided).
+ * @param {jQuery/jqLite element} element the element which will be removed from the DOM
+ * @param {function=} done callback function that will be called after the element has been
+ * removed from the DOM
+ */
+ leave : function(element, done) {
+ element.remove();
+ done && $timeout(done, 0, false);
+ },
- function hide(element) {
- element.css('display', 'none');
- }
+ /**
+ *
+ * @ngdoc function
+ * @name ng.$animate#move
+ * @methodOf ng.$animate
+ * @function
+ * @description Moves the position of the provided element within the DOM to be placed
+ * either after the `after` element or inside of the `parent` element. Once complete, the
+ * done() callback will be fired (if provided).
+ *
+ * @param {jQuery/jqLite element} element the element which will be moved around within the
+ * DOM
+ * @param {jQuery/jqLite element} parent the parent element where the element will be
+ * inserted into (if the after element is not present)
+ * @param {jQuery/jqLite element} after the sibling element where the element will be
+ * positioned next to
+ * @param {function=} done the callback function (if provided) that will be fired after the
+ * element has been moved to its new position
+ */
+ move : function(element, parent, after, done) {
+ // Do not remove element before insert. Removing will cause data associated with the
+ // element to be dropped. Insert will implicitly do the remove.
+ this.enter(element, parent, after, done);
+ },
- function insert(element, parent, after) {
- if (after) {
- after.after(element);
- } else {
- parent.append(element);
- }
- }
+ /**
+ *
+ * @ngdoc function
+ * @name ng.$animate#addClass
+ * @methodOf ng.$animate
+ * @function
+ * @description Adds the provided className CSS class value to the provided element. Once
+ * complete, the done() callback will be fired (if provided).
+ * @param {jQuery/jqLite element} element the element which will have the className value
+ * added to it
+ * @param {string} className the CSS class which will be added to the element
+ * @param {function=} done the callback function (if provided) that will be fired after the
+ * className value has been added to the element
+ */
+ addClass : function(element, className, done) {
+ className = isString(className) ?
+ className :
+ isArray(className) ? className.join(' ') : '';
+ forEach(element, function (element) {
+ jqLiteAddClass(element, className);
+ });
+ done && $timeout(done, 0, false);
+ },
- function remove(element) {
- element.remove();
- }
+ /**
+ *
+ * @ngdoc function
+ * @name ng.$animate#removeClass
+ * @methodOf ng.$animate
+ * @function
+ * @description Removes the provided className CSS class value from the provided element.
+ * Once complete, the done() callback will be fired (if provided).
+ * @param {jQuery/jqLite element} element the element which will have the className value
+ * removed from it
+ * @param {string} className the CSS class which will be removed from the element
+ * @param {function=} done the callback function (if provided) that will be fired after the
+ * className value has been removed from the element
+ */
+ removeClass : function(element, className, done) {
+ className = isString(className) ?
+ className :
+ isArray(className) ? className.join(' ') : '';
+ forEach(element, function (element) {
+ jqLiteRemoveClass(element, className);
+ });
+ done && $timeout(done, 0, false);
+ },
- function move(element, parent, after) {
- // Do not remove element before insert. Removing will cause data associated with the
- // element to be dropped. Insert will implicitly do the remove.
- insert(element, parent, after);
- }
+ enabled : noop
+ };
}];
-};
+}];
/**
* ! This is a private undocumented service !
@@ -3469,7 +4186,8 @@ function Browser(window, document, $log, $sniffer) {
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
- baseElement = document.find('base');
+ baseElement = document.find('base'),
+ newLocation = null;
/**
* @name ng.$browser#url
@@ -3492,6 +4210,10 @@ function Browser(window, document, $log, $sniffer) {
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
+ // Android Browser BFCache causes location, history reference to become stale.
+ if (location !== window.location) location = window.location;
+ if (history !== window.history) history = window.history;
+
// setter
if (url) {
if (lastBrowserUrl == url) return;
@@ -3504,14 +4226,20 @@ function Browser(window, document, $log, $sniffer) {
baseElement.attr('href', baseElement.attr('href'));
}
} else {
- if (replace) location.replace(url);
- else location.href = url;
+ newLocation = url;
+ if (replace) {
+ location.replace(url);
+ } else {
+ location.href = url;
+ }
}
return self;
// getter
} else {
- // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
- return location.href.replace(/%27/g,"'");
+ // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
+ // methods not updating location.href synchronously.
+ // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
+ return newLocation || location.href.replace(/%27/g,"'");
}
};
@@ -3519,6 +4247,7 @@ function Browser(window, document, $log, $sniffer) {
urlChangeInit = false;
function fireUrlChange() {
+ newLocation = null;
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
@@ -3535,7 +4264,7 @@ function Browser(window, document, $log, $sniffer) {
* @description
* Register callback function that will be called, when url changes.
*
- * It's only called when the url is changed by outside of angular:
+ * It's only called when the url is changed from outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
@@ -3557,9 +4286,9 @@ function Browser(window, document, $log, $sniffer) {
// changed by push/replaceState
// html5 history api - popstate event
- if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
+ if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
// hashchange event
- if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
+ if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
@@ -3575,14 +4304,18 @@ function Browser(window, document, $log, $sniffer) {
//////////////////////////////////////////////////////////////
/**
+ * @name ng.$browser#baseHref
+ * @methodOf ng.$browser
+ *
+ * @description
* Returns current
* (always relative - without domain)
*
- * @returns {string=}
+ * @returns {string=} current
*/
self.baseHref = function() {
var href = baseElement.attr('href');
- return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
+ return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
};
//////////////////////////////////////////////////////////////
@@ -3604,30 +4337,35 @@ function Browser(window, document, $log, $sniffer) {
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
- *
- *
cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it
- *
cookies(name, value) -> set name to value, if value is undefined delete the cookie
- *
cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)
- *
+ *
+ * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
+ * it
+ * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
+ * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
+ * way)
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
+ /* global escape: false, unescape: false */
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
- rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
+ rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
+ ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
- cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
+ cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
+ ';path=' + cookiePath).length + 1;
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
// - 300 cookies
// - 20 cookies per unique domain
// - 4096 bytes per cookie
if (cookieLength > 4096) {
- $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
+ $log.warn("Cookie '"+ name +
+ "' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
}
@@ -3642,7 +4380,13 @@ function Browser(window, document, $log, $sniffer) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
- lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1));
+ name = unescape(cookie.substring(0, index));
+ // the first value that is seen for a cookie is the most
+ // specific one. values for the same cookie name that
+ // follow are for less specific paths.
+ if (lastCookies[name] === undefined) {
+ lastCookies[name] = unescape(cookie.substring(index + 1));
+ }
}
}
}
@@ -3654,7 +4398,7 @@ function Browser(window, document, $log, $sniffer) {
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
- * @param {function()} fn A function, who's execution should be defered.
+ * @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
@@ -3683,10 +4427,11 @@ function Browser(window, document, $log, $sniffer) {
* @methodOf ng.$browser.defer
*
* @description
- * Cancels a defered task identified with `deferId`.
+ * Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
- * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
+ * canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
@@ -3712,7 +4457,21 @@ function $BrowserProvider(){
* @name ng.$cacheFactory
*
* @description
- * Factory that constructs cache objects.
+ * Factory that constructs cache objects and gives access to them.
+ *
+ *
*
*
* @param {string} cacheId Name or id of the newly created cache.
@@ -3723,7 +4482,8 @@ function $BrowserProvider(){
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
- * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it.
+ * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
+ * it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
@@ -3737,7 +4497,7 @@ function $CacheFactoryProvider() {
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
- throw Error('cacheId ' + cacheId + ' taken');
+ throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
}
var size = 0,
@@ -3846,6 +4606,16 @@ function $CacheFactoryProvider() {
}
+ /**
+ * @ngdoc method
+ * @name ng.$cacheFactory#info
+ * @methodOf ng.$cacheFactory
+ *
+ * @description
+ * Get information about all the of the caches that have been created
+ *
+ * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
+ */
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
@@ -3855,6 +4625,17 @@ function $CacheFactoryProvider() {
};
+ /**
+ * @ngdoc method
+ * @name ng.$cacheFactory#get
+ * @methodOf ng.$cacheFactory
+ *
+ * @description
+ * Get access to a cache object by the `cacheId` used when it was created.
+ *
+ * @param {string} cacheId Name or id of a cache to access.
+ * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
+ */
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
@@ -3869,8 +4650,44 @@ function $CacheFactoryProvider() {
* @name ng.$templateCache
*
* @description
- * Cache used for storing html templates.
- *
+ * The first time a template is used, it is loaded in the template cache for quick retrieval. You
+ * can load templates directly into the cache in a `script` tag, or by consuming the
+ * `$templateCache` service directly.
+ *
+ * Adding via the `script` tag:
+ *
+ *
+ *
+ *
+ *
+ * ...
+ *
+ *
+ *
+ * **Note:** the `script` tag containing the template does not need to be included in the `head` of
+ * the document, but it must be below the `ng-app` definition.
+ *
+ * Adding via the $templateCache service:
+ *
+ *
+ * var myApp = angular.module('myApp', []);
+ * myApp.run(function($templateCache) {
+ * $templateCache.put('templateId.html', 'This is the content of the template');
+ * });
+ *
+ *
+ * To retrieve the template later, simply use it in your HTML:
+ *
+ *
+ *
+ *
+ * or get it via Javascript:
+ *
+ * $templateCache.get('templateId.html')
+ *
+ *
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
@@ -3898,31 +4715,374 @@ function $TemplateCacheProvider() {
*/
-var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
-
-
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
- * Compiles a piece of HTML string or DOM into a template and produces a template function, which
- * can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
+ * Compiles an HTML string or DOM into a template and produces a template function, which
+ * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
*
- * The compilation is a process of walking the DOM tree and trying to match DOM elements to
- * {@link ng.$compileProvider#directive directives}. For each match it
- * executes corresponding template function and collects the
- * instance functions into a single template function which is then returned.
+ * The compilation is a process of walking the DOM tree and matching DOM elements to
+ * {@link ng.$compileProvider#methods_directive directives}.
*
- * The template function can then be used once to produce the view or as it is the case with
- * {@link ng.directive:ngRepeat repeater} many-times, in which
- * case each call results in a view that is a DOM clone of the original template.
+ *
+ * **Note:** This document is an in-depth reference of all directive options.
+ * For a gentle introduction to directives with examples of common use cases,
+ * see the {@link guide/directive directive guide}.
+ *
+ *
+ * ## Comprehensive Directive API
+ *
+ * There are many different options for a directive.
+ *
+ * The difference resides in the return value of the factory function.
+ * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
+ * or just the `postLink` function (all other properties will have the default values).
+ *
+ *
+ * **Best Practice:** It's recommended to use the "directive definition object" form.
+ *
+ *
+ * Here's an example directive declared with a Directive Definition Object:
+ *
+ *
+ * **Note:** Any unspecified options will use the default value. You can see the default values below.
+ *
+ *
+ * Therefore the above can be simplified as:
+ *
+ *
+ * var myModule = angular.module(...);
+ *
+ * myModule.directive('directiveName', function factory(injectables) {
+ * var directiveDefinitionObject = {
+ * link: function postLink(scope, iElement, iAttrs) { ... }
+ * };
+ * return directiveDefinitionObject;
+ * // or
+ * // return function postLink(scope, iElement, iAttrs) { ... }
+ * });
+ *
+ *
+ *
+ *
+ * ### Directive Definition Object
+ *
+ * The directive definition object provides instructions to the {@link api/ng.$compile
+ * compiler}. The attributes are:
+ *
+ * #### `priority`
+ * When there are multiple directives defined on a single DOM element, sometimes it
+ * is necessary to specify the order in which the directives are applied. The `priority` is used
+ * to sort the directives before their `compile` functions get called. Priority is defined as a
+ * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
+ * are also run in priority order, but post-link functions are run in reverse order. The order
+ * of directives with the same priority is undefined. The default priority is `0`.
+ *
+ * #### `terminal`
+ * If set to true then the current `priority` will be the last set of directives
+ * which will execute (any directives at the current priority will still execute
+ * as the order of execution on same `priority` is undefined).
+ *
+ * #### `scope`
+ * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
+ * same element request a new scope, only one new scope is created. The new scope rule does not
+ * apply for the root of the template since the root of the template always gets a new scope.
+ *
+ * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
+ * normal scope in that it does not prototypically inherit from the parent scope. This is useful
+ * when creating reusable components, which should not accidentally read or modify data in the
+ * parent scope.
+ *
+ * The 'isolate' scope takes an object hash which defines a set of local scope properties
+ * derived from the parent scope. These local properties are useful for aliasing values for
+ * templates. Locals definition is a hash of local scope property to its source:
+ *
+ * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
+ * always a string since DOM attributes are strings. If no `attr` name is specified then the
+ * attribute name is assumed to be the same as the local name.
+ * Given `` and widget definition
+ * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
+ * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
+ * `localName` property on the widget scope. The `name` is read from the parent scope (not
+ * component scope).
+ *
+ * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
+ * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
+ * name is specified then the attribute name is assumed to be the same as the local name.
+ * Given `` and widget definition of
+ * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
+ * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
+ * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
+ * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
+ * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
+ *
+ * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
+ * If no `attr` name is specified then the attribute name is assumed to be the same as the
+ * local name. Given `` and widget definition of
+ * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
+ * a function wrapper for the `count = count + value` expression. Often it's desirable to
+ * pass data from the isolated scope via an expression and to the parent scope, this can be
+ * done by passing a map of local variable names and values into the expression wrapper fn.
+ * For example, if the expression is `increment(amount)` then we can specify the amount value
+ * by calling the `localFn` as `localFn({amount: 22})`.
+ *
+ *
+ *
+ * #### `controller`
+ * Controller constructor function. The controller is instantiated before the
+ * pre-linking phase and it is shared with other directives (see
+ * `require` attribute). This allows the directives to communicate with each other and augment
+ * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
+ *
+ * * `$scope` - Current scope associated with the element
+ * * `$element` - Current element
+ * * `$attrs` - Current attributes object for the element
+ * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
+ * The scope can be overridden by an optional first argument.
+ * `function([scope], cloneLinkingFn)`.
+ *
+ *
+ * #### `require`
+ * Require another directive and inject its controller as the fourth argument to the linking function. The
+ * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
+ * injected argument will be an array in corresponding order. If no such directive can be
+ * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
+ *
+ * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
+ * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
+ * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
+ * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
+ * `link` fn if not found.
+ *
+ *
+ * #### `controllerAs`
+ * Controller alias at the directive scope. An alias for the controller so it
+ * can be referenced at the directive template. The directive needs to define a scope for this
+ * configuration to be used. Useful in the case when directive is used as component.
+ *
+ *
+ * #### `restrict`
+ * String of subset of `EACM` which restricts the directive to a specific directive
+ * declaration style. If omitted, the default (attributes only) is used.
+ *
+ * * `E` - Element name: ``
+ * * `A` - Attribute (default): ``
+ * * `C` - Class: ``
+ * * `M` - Comment: ``
+ *
+ *
+ * #### `template`
+ * replace the current element with the contents of the HTML. The replacement process
+ * migrates all of the attributes / classes from the old element to the new one. See the
+ * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
+ * Directives Guide} for an example.
+ *
+ * You can specify `template` as a string representing the template or as a function which takes
+ * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
+ * returns a string value representing the template.
+ *
+ *
+ * #### `templateUrl`
+ * Same as `template` but the template is loaded from the specified URL. Because
+ * the template loading is asynchronous the compilation/linking is suspended until the template
+ * is loaded.
+ *
+ * You can specify `templateUrl` as a string representing the URL or as a function which takes two
+ * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
+ * a string value representing the url. In either case, the template URL is passed through {@link
+ * api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}.
+ *
+ *
+ * #### `replace`
+ * specify where the template should be inserted. Defaults to `false`.
+ *
+ * * `true` - the template will replace the current element.
+ * * `false` - the template will replace the contents of the current element.
+ *
+ *
+ * #### `transclude`
+ * compile the content of the element and make it available to the directive.
+ * Typically used with {@link api/ng.directive:ngTransclude
+ * ngTransclude}. The advantage of transclusion is that the linking function receives a
+ * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
+ * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
+ * scope. This makes it possible for the widget to have private state, and the transclusion to
+ * be bound to the parent (pre-`isolate`) scope.
+ *
+ * * `true` - transclude the content of the directive.
+ * * `'element'` - transclude the whole element including any directives defined at lower priority.
+ *
+ *
+ * #### `compile`
+ *
+ *
+ *
+ * The compile function deals with transforming the template DOM. Since most directives do not do
+ * template transformation, it is not used often. Examples that require compile functions are
+ * directives that transform template DOM, such as {@link
+ * api/ng.directive:ngRepeat ngRepeat}, or load the contents
+ * asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The
+ * compile function takes the following arguments.
+ *
+ * * `tElement` - template element - The element where the directive has been declared. It is
+ * safe to do template transformation on the element and child elements only.
+ *
+ * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
+ * between all directive compile functions.
+ *
+ * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
+ *
+ *
+ * **Note:** The template instance and the link instance may be different objects if the template has
+ * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
+ * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
+ * should be done in a linking function rather than in a compile function.
+ *
+ *
+ *
+ * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
+ * e.g. does not know about the right outer scope. Please use the transclude function that is passed
+ * to the link function instead.
+ *
+
+ * A compile function can have a return value which can be either a function or an object.
+ *
+ * * returning a (post-link) function - is equivalent to registering the linking function via the
+ * `link` property of the config object when the compile function is empty.
+ *
+ * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
+ * control when a linking function should be called during the linking phase. See info about
+ * pre-linking and post-linking functions below.
+ *
+ *
+ * #### `link`
+ * This property is used only if the `compile` property is not defined.
+ *
+ *
+ *
+ * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
+ * executed after the template has been cloned. This is where most of the directive logic will be
+ * put.
+ *
+ * * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
+ * directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}.
+ *
+ * * `iElement` - instance element - The element where the directive is to be used. It is safe to
+ * manipulate the children of the element only in `postLink` function since the children have
+ * already been linked.
+ *
+ * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
+ * between all directive linking functions.
+ *
+ * * `controller` - a controller instance - A controller instance if at least one directive on the
+ * element defines a controller. The controller is shared among all the directives, which allows
+ * the directives to use the controllers as a communication channel.
+ *
+ * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
+ * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
+ * parameter of directive controllers.
+ * `function([scope], cloneLinkingFn)`.
+ *
+ *
+ * #### Pre-linking function
+ *
+ * Executed before the child elements are linked. Not safe to do DOM transformation since the
+ * compiler linking function will fail to locate the correct elements for linking.
+ *
+ * #### Post-linking function
+ *
+ * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
+ *
+ *
+ * ### Attributes
+ *
+ * The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
+ * `link()` or `compile()` functions. It has a variety of uses.
+ *
+ * accessing *Normalized attribute names:*
+ * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
+ * the attributes object allows for normalized access to
+ * the attributes.
+ *
+ * * *Directive inter-communication:* All directives share the same instance of the attributes
+ * object which allows the directives to use the attributes object as inter directive
+ * communication.
+ *
+ * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
+ * allowing other directives to read the interpolated value.
+ *
+ * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
+ * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
+ * the only way to easily get the actual value because during the linking phase the interpolation
+ * hasn't been evaluated yet and so the value is at this time set to `undefined`.
+ *
+ *
+ * function linkingFn(scope, elm, attrs, ctrl) {
+ * // get the attribute value
+ * console.log(attrs.ngModel);
+ *
+ * // change the attribute
+ * attrs.$set('ngModel', 'new value');
+ *
+ * // observe changes to interpolated attribute
+ * attrs.$observe('ngModel', function(value) {
+ * console.log('ngModel has changed value to ' + value);
+ * });
+ * }
+ *
+ *
+ * Below is an example using `$compileProvider`.
+ *
+ *
+ * **Note**: Typically directives are registered with `module.directive`. The example below is
+ * to illustrate how `$compile` works.
+ *
*
+
+ //demo.label//
+
+
+
+ it('should interpolate binding with custom symbols', function() {
+ expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
+ });
+
+
*/
function $InterpolateProvider() {
var startSymbol = '{{';
@@ -5273,7 +8156,7 @@ function $InterpolateProvider() {
};
- this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) {
+ this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
@@ -5283,6 +8166,7 @@ function $InterpolateProvider() {
* @function
*
* @requires $parse
+ * @requires $sce
*
* @description
*
@@ -5294,8 +8178,8 @@ function $InterpolateProvider() {
*
var $interpolate = ...; // injected
- var exp = $interpolate('Hello {{name}}!');
- expect(exp({name:'Angular'}).toEqual('Hello Angular!');
+ var exp = $interpolate('Hello {{name | uppercase}}!');
+ expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
*
*
@@ -5303,14 +8187,18 @@ function $InterpolateProvider() {
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
- * @returns {function(context)} an interpolation function which is used to compute the interpolated
- * string. The function has these parameters:
+ * @param {string=} trustedContext when provided, the returned function passes the interpolated
+ * result through {@link ng.$sce#methods_getTrusted $sce.getTrusted(interpolatedResult,
+ * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
+ * provides Strict Contextual Escaping for details.
+ * @returns {function(context)} an interpolation function which is used to compute the
+ * interpolated string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
- function $interpolate(text, mustHaveExpression) {
+ function $interpolate(text, mustHaveExpression, trustedContext) {
var startIndex,
endIndex,
index = 0,
@@ -5342,6 +8230,19 @@ function $InterpolateProvider() {
length = 1;
}
+ // Concatenating expressions makes it hard to reason about whether some combination of
+ // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
+ // single expression be used for iframe[src], object[src], etc., we ensure that the value
+ // that's used is assigned or constructed by some JS code somewhere that is more testable or
+ // make it obvious that you bound the value to some user controlled value. This helps reduce
+ // the load when auditing for XSS issues.
+ if (trustedContext && parts.length > 1) {
+ throw $interpolateMinErr('noconcat',
+ "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
+ "interpolations that concatenate multiple expressions when a trusted value is " +
+ "required. See http://docs.angularjs.org/api/ng.$sce", text);
+ }
+
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
@@ -5349,7 +8250,12 @@ function $InterpolateProvider() {
for(var i = 0, ii = length, part; i
+ * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
+ * with them. In particular they are not automatically destroyed when a controller's scope or a
+ * directive's element are destroyed.
+ * You should take this into consideration and make sure to always cancel the interval at the
+ * appropriate moment. See the example below for more details on how and when to do this.
+ *
+ *
+ * @param {function()} fn A function that should be called repeatedly.
+ * @param {number} delay Number of milliseconds between each function call.
+ * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
+ * indefinitely.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
+ * @returns {promise} A promise which will be notified on each iteration.
+ *
+ * @example
+
+
+
+
+
+
+ Date format:
+ Current time is:
+
+ Blood 1 : {{blood_1}}
+ Blood 2 : {{blood_2}}
+
+
+
+
+
+
+
+
+ */
+ function interval(fn, delay, count, invokeApply) {
+ var setInterval = $window.setInterval,
+ clearInterval = $window.clearInterval,
+ deferred = $q.defer(),
+ promise = deferred.promise,
+ iteration = 0,
+ skipApply = (isDefined(invokeApply) && !invokeApply);
+
+ count = isDefined(count) ? count : 0;
+
+ promise.then(null, null, fn);
+
+ promise.$$intervalId = setInterval(function tick() {
+ deferred.notify(iteration++);
+
+ if (count > 0 && iteration >= count) {
+ deferred.resolve(iteration);
+ clearInterval(promise.$$intervalId);
+ delete intervals[promise.$$intervalId];
+ }
+
+ if (!skipApply) $rootScope.$apply();
+
+ }, delay);
+
+ intervals[promise.$$intervalId] = deferred;
+
+ return promise;
+ }
+
+
+ /**
+ * @ngdoc function
+ * @name ng.$interval#cancel
+ * @methodOf ng.$interval
+ *
+ * @description
+ * Cancels a task associated with the `promise`.
+ *
+ * @param {number} promise Promise returned by the `$interval` function.
+ * @returns {boolean} Returns `true` if the task was successfully canceled.
+ */
+ interval.cancel = function(promise) {
+ if (promise && promise.$$intervalId in intervals) {
+ intervals[promise.$$intervalId].reject('canceled');
+ clearInterval(promise.$$intervalId);
+ delete intervals[promise.$$intervalId];
+ return true;
+ }
+ return false;
+ };
+
+ return interval;
+ }];
+}
+
+/**
+ * @ngdoc object
+ * @name ng.$locale
+ *
+ * @description
+ * $locale service provides localization rules for various Angular components. As of right now the
+ * only public api is:
+ *
+ * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
+ */
+function $LocaleProvider(){
+ this.$get = function() {
+ return {
+ id: 'en-us',
+
+ NUMBER_FORMATS: {
+ DECIMAL_SEP: '.',
+ GROUP_SEP: ',',
+ PATTERNS: [
+ { // Decimal Pattern
+ minInt: 1,
+ minFrac: 0,
+ maxFrac: 3,
+ posPre: '',
+ posSuf: '',
+ negPre: '-',
+ negSuf: '',
+ gSize: 3,
+ lgSize: 3
+ },{ //Currency Pattern
+ minInt: 1,
+ minFrac: 2,
+ maxFrac: 2,
+ posPre: '\u00A4',
+ posSuf: '',
+ negPre: '(\u00A4',
+ negSuf: ')',
+ gSize: 3,
+ lgSize: 3
+ }
+ ],
+ CURRENCY_SYM: '$'
+ },
+
+ DATETIME_FORMATS: {
+ MONTH:
+ 'January,February,March,April,May,June,July,August,September,October,November,December'
+ .split(','),
+ SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
+ DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
+ SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
+ AMPMS: ['AM','PM'],
+ medium: 'MMM d, y h:mm:ss a',
+ short: 'M/d/yy h:mm a',
+ fullDate: 'EEEE, MMMM d, y',
+ longDate: 'MMMM d, y',
+ mediumDate: 'MMM d, y',
+ shortDate: 'M/d/yy',
+ mediumTime: 'h:mm:ss a',
+ shortTime: 'h:mm a'
+ },
+
+ pluralCat: function(num) {
+ if (num === 1) {
+ return 'one';
+ }
+ return 'other';
+ }
+ };
+ };
+}
+
+var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
+var $locationMinErr = minErr('$location');
/**
@@ -5431,108 +8594,95 @@ function encodePath(path) {
return segments.join('/');
}
-function stripHash(url) {
- return url.split('#')[0];
+function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
+ var parsedUrl = urlResolve(absoluteUrl, appBase);
+
+ locationObj.$$protocol = parsedUrl.protocol;
+ locationObj.$$host = parsedUrl.hostname;
+ locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
}
-function matchUrl(url, obj) {
- var match = URL_MATCH.exec(url);
-
- match = {
- protocol: match[1],
- host: match[3],
- port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
- path: match[6] || '/',
- search: match[8],
- hash: match[10]
- };
-
- if (obj) {
- obj.$$protocol = match.protocol;
- obj.$$host = match.host;
- obj.$$port = match.port;
+function parseAppUrl(relativeUrl, locationObj, appBase) {
+ var prefixed = (relativeUrl.charAt(0) !== '/');
+ if (prefixed) {
+ relativeUrl = '/' + relativeUrl;
}
+ var match = urlResolve(relativeUrl, appBase);
+ locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
+ match.pathname.substring(1) : match.pathname);
+ locationObj.$$search = parseKeyValue(match.search);
+ locationObj.$$hash = decodeURIComponent(match.hash);
- return match;
-}
-
-
-function composeProtocolHostPort(protocol, host, port) {
- return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
-}
-
-
-function pathPrefixFromBase(basePath) {
- return basePath.substr(0, basePath.lastIndexOf('/'));
-}
-
-
-function convertToHtml5Url(url, basePath, hashPrefix) {
- var match = matchUrl(url);
-
- // already html5 url
- if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
- match.hash.indexOf(hashPrefix) !== 0) {
- return url;
- // convert hashbang url -> html5 url
- } else {
- return composeProtocolHostPort(match.protocol, match.host, match.port) +
- pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
- }
-}
-
-
-function convertToHashbangUrl(url, basePath, hashPrefix) {
- var match = matchUrl(url);
-
- // already hashbang url
- if (decodeURIComponent(match.path) == basePath && !isUndefined(match.hash) &&
- match.hash.indexOf(hashPrefix) === 0) {
- return url;
- // convert html5 url -> hashbang url
- } else {
- var search = match.search && '?' + match.search || '',
- hash = match.hash && '#' + match.hash || '',
- pathPrefix = pathPrefixFromBase(basePath),
- path = match.path.substr(pathPrefix.length);
-
- if (match.path.indexOf(pathPrefix) !== 0) {
- throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
- }
-
- return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
- '#' + hashPrefix + path + search + hash;
+ // make sure path starts with '/';
+ if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
+ locationObj.$$path = '/' + locationObj.$$path;
}
}
/**
- * LocationUrl represents an url
+ *
+ * @param {string} begin
+ * @param {string} whole
+ * @returns {string} returns text from whole after begin or undefined if it does not begin with
+ * expected string.
+ */
+function beginsWith(begin, whole) {
+ if (whole.indexOf(begin) === 0) {
+ return whole.substr(begin.length);
+ }
+}
+
+
+function stripHash(url) {
+ var index = url.indexOf('#');
+ return index == -1 ? url : url.substr(0, index);
+}
+
+
+function stripFile(url) {
+ return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
+}
+
+/* return the server only (scheme://host:port) */
+function serverBase(url) {
+ return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
+}
+
+
+/**
+ * LocationHtml5Url represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
- * @param {string} url HTML5 url
- * @param {string} pathPrefix
+ * @param {string} appBase application base URL
+ * @param {string} basePrefix url path prefix
*/
-function LocationUrl(url, pathPrefix, appBaseUrl) {
- pathPrefix = pathPrefix || '';
+function LocationHtml5Url(appBase, basePrefix) {
+ this.$$html5 = true;
+ basePrefix = basePrefix || '';
+ var appBaseNoFile = stripFile(appBase);
+ parseAbsoluteUrl(appBase, this, appBase);
+
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
- this.$$parse = function(newAbsoluteUrl) {
- var match = matchUrl(newAbsoluteUrl, this);
-
- if (match.path.indexOf(pathPrefix) !== 0) {
- throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
+ this.$$parse = function(url) {
+ var pathUrl = beginsWith(appBaseNoFile, url);
+ if (!isString(pathUrl)) {
+ throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
+ appBaseNoFile);
}
- this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
- this.$$search = parseKeyValue(match.search);
- this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
+ parseAppUrl(pathUrl, this, appBase);
+
+ if (!this.$$path) {
+ this.$$path = '/';
+ }
this.$$compose();
};
@@ -5546,32 +8696,42 @@ function LocationUrl(url, pathPrefix, appBaseUrl) {
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
- this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
- pathPrefix + this.$$url;
+ this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
};
+ this.$$rewrite = function(url) {
+ var appUrl, prevAppUrl;
- this.$$rewriteAppUrl = function(absoluteLinkUrl) {
- if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
- return absoluteLinkUrl;
+ if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
+ prevAppUrl = appUrl;
+ if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
+ return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
+ } else {
+ return appBase + prevAppUrl;
+ }
+ } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
+ return appBaseNoFile + appUrl;
+ } else if (appBaseNoFile == url + '/') {
+ return appBaseNoFile;
}
- }
-
-
- this.$$parse(url);
+ };
}
/**
* LocationHashbangUrl represents url
- * This object is exposed as $location service when html5 history api is disabled or not supported
+ * This object is exposed as $location service when developer doesn't opt into html5 mode.
+ * It also serves as the base class for html5 mode fallback on legacy browsers.
*
* @constructor
- * @param {string} url Legacy url
- * @param {string} hashPrefix Prefix for hash part (containing path and search)
+ * @param {string} appBase application base URL
+ * @param {string} hashPrefix hashbang prefix
*/
-function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
- var basePath;
+function LocationHashbangUrl(appBase, hashPrefix) {
+ var appBaseNoFile = stripFile(appBase);
+
+ parseAbsoluteUrl(appBase, this, appBase);
+
/**
* Parse given hashbang url into properties
@@ -5579,25 +8739,59 @@ function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
* @private
*/
this.$$parse = function(url) {
- var match = matchUrl(url, this);
+ var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
+ var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
+ ? beginsWith(hashPrefix, withoutBaseUrl)
+ : (this.$$html5)
+ ? withoutBaseUrl
+ : '';
-
- if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
- throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
+ if (!isString(withoutHashUrl)) {
+ throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
+ hashPrefix);
}
+ parseAppUrl(withoutHashUrl, this, appBase);
- basePath = match.path + (match.search ? '?' + match.search : '');
- match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
- if (match[1]) {
- this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
- } else {
- this.$$path = '';
- }
-
- this.$$search = parseKeyValue(match[3]);
- this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
+ this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
this.$$compose();
+
+ /*
+ * In Windows, on an anchor node on documents loaded from
+ * the filesystem, the browser will return a pathname
+ * prefixed with the drive name ('/C:/path') when a
+ * pathname without a drive is set:
+ * * a.setAttribute('href', '/foo')
+ * * a.pathname === '/C:/foo' //true
+ *
+ * Inside of Angular, we're always using pathnames that
+ * do not include drive names for routing.
+ */
+ function removeWindowsDriveName (path, url, base) {
+ /*
+ Matches paths for file protocol on windows,
+ such as /C:/foo/bar, and captures only /foo/bar.
+ */
+ var windowsFilePathExp = /^\/?.*?:(\/.*)/;
+
+ var firstPathSegmentMatch;
+
+ //Get the relative path from the input URL.
+ if (url.indexOf(base) === 0) {
+ url = url.replace(base, '');
+ }
+
+ /*
+ * The input URL intentionally contains a
+ * first path segment that ends with a colon.
+ */
+ if (windowsFilePathExp.exec(url)) {
+ return path;
+ }
+
+ firstPathSegmentMatch = windowsFilePathExp.exec(path);
+ return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
+ }
};
/**
@@ -5609,22 +8803,55 @@ function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
- this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
- basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
+ this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
};
- this.$$rewriteAppUrl = function(absoluteLinkUrl) {
- if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
- return absoluteLinkUrl;
+ this.$$rewrite = function(url) {
+ if(stripHash(appBase) == stripHash(url)) {
+ return url;
}
- }
-
-
- this.$$parse(url);
+ };
}
-LocationUrl.prototype = {
+/**
+ * LocationHashbangUrl represents url
+ * This object is exposed as $location service when html5 history api is enabled but the browser
+ * does not support it.
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} hashPrefix hashbang prefix
+ */
+function LocationHashbangInHtml5Url(appBase, hashPrefix) {
+ this.$$html5 = true;
+ LocationHashbangUrl.apply(this, arguments);
+
+ var appBaseNoFile = stripFile(appBase);
+
+ this.$$rewrite = function(url) {
+ var appUrl;
+
+ if ( appBase == stripHash(url) ) {
+ return url;
+ } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
+ return appBase + hashPrefix + appUrl;
+ } else if ( appBaseNoFile === url + '/') {
+ return appBaseNoFile;
+ }
+ };
+}
+
+
+LocationHashbangInHtml5Url.prototype =
+ LocationHashbangUrl.prototype =
+ LocationHtml5Url.prototype = {
+
+ /**
+ * Are we in html5 mode?
+ * @private
+ */
+ $$html5: false,
/**
* Has any change been replacing ?
@@ -5660,6 +8887,7 @@ LocationUrl.prototype = {
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
+ * @param {string=} replace The path that will be changed
* @return {string} url
*/
url: function(url, replace) {
@@ -5750,24 +8978,36 @@ LocationUrl.prototype = {
*
* Change search part when called with parameter and return `$location`.
*
- * @param {string|object=} search New search params - string or hash object
- * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
- * single search parameter. If the value is `null`, the parameter will be deleted.
+ * @param {string|Object.|Object.>} search New search params - string or
+ * hash object. Hash object may contain an array of values, which will be decoded as duplicates in
+ * the url.
+ *
+ * @param {(string|Array)=} paramValue If `search` is a string, then `paramValue` will override only a
+ * single search parameter. If `paramValue` is an array, it will set the parameter as a
+ * comma-separated value. If `paramValue` is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
- if (isUndefined(search))
- return this.$$search;
-
- if (isDefined(paramValue)) {
- if (paramValue === null) {
- delete this.$$search[search];
- } else {
- this.$$search[search] = paramValue;
- }
- } else {
- this.$$search = isString(search) ? parseKeyValue(search) : search;
+ switch (arguments.length) {
+ case 0:
+ return this.$$search;
+ case 1:
+ if (isString(search)) {
+ this.$$search = parseKeyValue(search);
+ } else if (isObject(search)) {
+ this.$$search = search;
+ } else {
+ throw $locationMinErr('isrcharg',
+ 'The first argument of the `$location#search()` call must be a string or an object.');
+ }
+ break;
+ default:
+ if (isUndefined(paramValue) || paramValue === null) {
+ delete this.$$search[search];
+ } else {
+ this.$$search[search] = paramValue;
+ }
}
this.$$compose();
@@ -5806,21 +9046,6 @@ LocationUrl.prototype = {
}
};
-LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
-
-function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
- LocationHashbangUrl.apply(this, arguments);
-
-
- this.$$rewriteAppUrl = function(absoluteLinkUrl) {
- if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
- return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
- }
- }
-}
-
-LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
-
function locationGetter(property) {
return function() {
return this[property];
@@ -5902,7 +9127,7 @@ function $LocationProvider(){
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
- * @param {string=} mode Use HTML5 strategy if available.
+ * @param {boolean=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
@@ -5914,42 +9139,54 @@ function $LocationProvider(){
}
};
+ /**
+ * @ngdoc event
+ * @name ng.$location#$locationChangeStart
+ * @eventOf ng.$location
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted before a URL will change. This change can be prevented by calling
+ * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
+ * details about event object. Upon successful change
+ * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {string} newUrl New URL
+ * @param {string=} oldUrl URL that was before it was changed.
+ */
+
+ /**
+ * @ngdoc event
+ * @name ng.$location#$locationChangeSuccess
+ * @eventOf ng.$location
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted after a URL was changed.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {string} newUrl New URL
+ * @param {string=} oldUrl URL that was before it was changed.
+ */
+
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
- basePath,
- pathPrefix,
- initUrl = $browser.url(),
- initUrlParts = matchUrl(initUrl),
- appBaseUrl;
+ LocationMode,
+ baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
+ initialUrl = $browser.url(),
+ appBase;
if (html5Mode) {
- basePath = $browser.baseHref() || '/';
- pathPrefix = pathPrefixFromBase(basePath);
- appBaseUrl =
- composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
- pathPrefix + '/';
-
- if ($sniffer.history) {
- $location = new LocationUrl(
- convertToHtml5Url(initUrl, basePath, hashPrefix),
- pathPrefix, appBaseUrl);
- } else {
- $location = new LocationHashbangInHtml5Url(
- convertToHashbangUrl(initUrl, basePath, hashPrefix),
- hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
- }
+ appBase = serverBase(initialUrl) + (baseHref || '/');
+ LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
} else {
- appBaseUrl =
- composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
- (initUrlParts.path || '') +
- (initUrlParts.search ? ('?' + initUrlParts.search) : '') +
- '#' + hashPrefix + '/';
-
- $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
+ appBase = stripHash(initialUrl);
+ LocationMode = LocationHashbangUrl;
}
+ $location = new LocationMode(appBase, '#' + hashPrefix);
+ $location.$$parse($location.$$rewrite(initialUrl));
- $rootElement.bind('click', function(event) {
+ $rootElement.on('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
@@ -5963,22 +9200,31 @@ function $LocationProvider(){
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
}
- var absHref = elm.prop('href'),
- rewrittenUrl = $location.$$rewriteAppUrl(absHref);
+ var absHref = elm.prop('href');
- if (absHref && !elm.attr('target') && rewrittenUrl) {
- // update location manually
- $location.$$parse(rewrittenUrl);
- $rootScope.$apply();
+ if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
+ // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
+ // an animation.
+ absHref = urlResolve(absHref.animVal).href;
+ }
+
+ var rewrittenUrl = $location.$$rewrite(absHref);
+
+ if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
event.preventDefault();
- // hack to work around FF6 bug 684208 when scenario runner clicks on links
- window.angular['ff-684208-preventDefault'] = true;
+ if (rewrittenUrl != $browser.url()) {
+ // update location manually
+ $location.$$parse(rewrittenUrl);
+ $rootScope.$apply();
+ // hack to work around FF6 bug 684208 when scenario runner clicks on links
+ window.angular['ff-684208-preventDefault'] = true;
+ }
}
});
// rewrite hashbang url <> html5 url
- if ($location.absUrl() != initUrl) {
+ if ($location.absUrl() != initialUrl) {
$browser.url($location.absUrl(), true);
}
@@ -5989,7 +9235,13 @@ function $LocationProvider(){
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
- afterLocationChange(oldUrl);
+ if ($rootScope.$broadcast('$locationChangeStart', newUrl,
+ oldUrl).defaultPrevented) {
+ $location.$$parse(oldUrl);
+ $browser.url(oldUrl);
+ } else {
+ afterLocationChange(oldUrl);
+ }
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
@@ -6032,11 +9284,14 @@ function $LocationProvider(){
* @requires $window
*
* @description
- * Simple service for logging. Default implementation writes the message
+ * Simple service for logging. Default implementation safely writes the message
* into the browser's console (if present).
- *
+ *
* The main purpose of this service is to simplify debugging and troubleshooting.
*
+ * The default is to log `debug` messages. You can use
+ * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
+ *
* @example
@@ -6074,16 +9329,16 @@ function $LogProvider(){
* @name ng.$logProvider#debugEnabled
* @methodOf ng.$logProvider
* @description
- * @param {string=} flag enable or disable debug level messages
+ * @param {boolean=} flag enable or disable debug level messages
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.debugEnabled = function(flag) {
- if (isDefined(flag)) {
- debug = flag;
- return this;
- } else {
- return debug;
- }
+ if (isDefined(flag)) {
+ debug = flag;
+ return this;
+ } else {
+ return debug;
+ }
};
this.$get = ['$window', function($window){
@@ -6098,16 +9353,6 @@ function $LogProvider(){
*/
log: consoleLog('log'),
- /**
- * @ngdoc method
- * @name ng.$log#warn
- * @methodOf ng.$log
- *
- * @description
- * Write a warning message
- */
- warn: consoleLog('warn'),
-
/**
* @ngdoc method
* @name ng.$log#info
@@ -6118,6 +9363,16 @@ function $LogProvider(){
*/
info: consoleLog('info'),
+ /**
+ * @ngdoc method
+ * @name ng.$log#warn
+ * @methodOf ng.$log
+ *
+ * @description
+ * Write a warning message
+ */
+ warn: consoleLog('warn'),
+
/**
* @ngdoc method
* @name ng.$log#error
@@ -6137,13 +9392,13 @@ function $LogProvider(){
* Write a debug message
*/
debug: (function () {
- var fn = consoleLog('debug');
-
- return function() {
- if (debug) {
- fn.apply(self, arguments);
- }
- }
+ var fn = consoleLog('debug');
+
+ return function() {
+ if (debug) {
+ fn.apply(self, arguments);
+ }
+ };
}())
};
@@ -6162,9 +9417,16 @@ function $LogProvider(){
function consoleLog(type) {
var console = $window.console || {},
- logFn = console[type] || console.log || noop;
+ logFn = console[type] || console.log || noop,
+ hasApply = false;
- if (logFn.apply) {
+ // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
+ // The reason behind this is that console.log has type "object" in IE8...
+ try {
+ hasApply = !! logFn.apply;
+ } catch (e) {}
+
+ if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
@@ -6177,13 +9439,78 @@ function $LogProvider(){
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
- logFn(arg1, arg2);
- }
+ logFn(arg1, arg2 == null ? '' : arg2);
+ };
}
}];
}
+var $parseMinErr = minErr('$parse');
+var promiseWarningCache = {};
+var promiseWarning;
+
+// Sandboxing Angular Expressions
+// ------------------------------
+// Angular expressions are generally considered safe because these expressions only have direct
+// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
+// obtaining a reference to native JS functions such as the Function constructor.
+//
+// As an example, consider the following Angular expression:
+//
+// {}.toString.constructor(alert("evil JS code"))
+//
+// We want to prevent this type of access. For the sake of performance, during the lexing phase we
+// disallow any "dotted" access to any member named "constructor".
+//
+// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor
+// while evaluating the expression, which is a stronger but more expensive test. Since reflective
+// calls are expensive anyway, this is not such a big deal compared to static dereferencing.
+//
+// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
+// against the expression language, but not to prevent exploits that were enabled by exposing
+// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
+// practice and therefore we are not even trying to protect against interaction with an object
+// explicitly exposed in this way.
+//
+// A developer could foil the name check by aliasing the Function constructor under a different
+// name on the scope.
+//
+// In general, it is not possible to access a Window object from an angular expression unless a
+// window or some DOM object that has a reference to window is published onto a Scope.
+
+function ensureSafeMemberName(name, fullExpression) {
+ if (name === "constructor") {
+ throw $parseMinErr('isecfld',
+ 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ }
+ return name;
+}
+
+function ensureSafeObject(obj, fullExpression) {
+ // nifty check if obj is Function that is fast and works across iframes and other contexts
+ if (obj) {
+ if (obj.constructor === obj) {
+ throw $parseMinErr('isecfn',
+ 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// isWindow(obj)
+ obj.document && obj.location && obj.alert && obj.setInterval) {
+ throw $parseMinErr('isecwindow',
+ 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// isElement(obj)
+ obj.children && (obj.nodeName || (obj.on && obj.find))) {
+ throw $parseMinErr('isecdom',
+ 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ }
+ }
+ return obj;
+}
+
var OPERATORS = {
+ /* jshint bitwise : false */
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
@@ -6197,7 +9524,10 @@ var OPERATORS = {
return a;
}
return isDefined(b)?b:undefined;},
- '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
+ '-':function(self, locals, a,b){
+ a=a(self, locals); b=b(self, locals);
+ return (isDefined(a)?a:0)-(isDefined(b)?b:0);
+ },
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
@@ -6218,158 +9548,196 @@ var OPERATORS = {
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
+/* jshint bitwise: true */
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
-function lex(text, csp){
- var tokens = [],
- token,
- index = 0,
- json = [],
- ch,
- lastCh = ':'; // can start regexp
- while (index < text.length) {
- ch = text.charAt(index);
- if (is('"\'')) {
- readString(ch);
- } else if (isNumber(ch) || is('.') && isNumber(peek())) {
- readNumber();
- } else if (isIdent(ch)) {
- readIdent();
- // identifiers can only be if the preceding char was a { or ,
- if (was('{,') && json[0]=='{' &&
- (token=tokens[tokens.length-1])) {
- token.json = token.text.indexOf('.') == -1;
- }
- } else if (is('(){}[].,;:')) {
- tokens.push({
- index:index,
- text:ch,
- json:(was(':[,') && is('{[')) || is('}]:,')
- });
- if (is('{[')) json.unshift(ch);
- if (is('}]')) json.shift();
- index++;
- } else if (isWhitespace(ch)) {
- index++;
- continue;
- } else {
- var ch2 = ch + peek(),
- ch3 = ch2 + peek(2),
- fn = OPERATORS[ch],
- fn2 = OPERATORS[ch2],
- fn3 = OPERATORS[ch3];
- if (fn3) {
- tokens.push({index:index, text:ch3, fn:fn3});
- index += 3;
- } else if (fn2) {
- tokens.push({index:index, text:ch2, fn:fn2});
- index += 2;
- } else if (fn) {
- tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
- index += 1;
+/////////////////////////////////////////
+
+
+/**
+ * @constructor
+ */
+var Lexer = function (options) {
+ this.options = options;
+};
+
+Lexer.prototype = {
+ constructor: Lexer,
+
+ lex: function (text) {
+ this.text = text;
+
+ this.index = 0;
+ this.ch = undefined;
+ this.lastCh = ':'; // can start regexp
+
+ this.tokens = [];
+
+ var token;
+ var json = [];
+
+ while (this.index < this.text.length) {
+ this.ch = this.text.charAt(this.index);
+ if (this.is('"\'')) {
+ this.readString(this.ch);
+ } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
+ this.readNumber();
+ } else if (this.isIdent(this.ch)) {
+ this.readIdent();
+ // identifiers can only be if the preceding char was a { or ,
+ if (this.was('{,') && json[0] === '{' &&
+ (token = this.tokens[this.tokens.length - 1])) {
+ token.json = token.text.indexOf('.') === -1;
+ }
+ } else if (this.is('(){}[].,;:?')) {
+ this.tokens.push({
+ index: this.index,
+ text: this.ch,
+ json: (this.was(':[,') && this.is('{[')) || this.is('}]:,')
+ });
+ if (this.is('{[')) json.unshift(this.ch);
+ if (this.is('}]')) json.shift();
+ this.index++;
+ } else if (this.isWhitespace(this.ch)) {
+ this.index++;
+ continue;
} else {
- throwError("Unexpected next character ", index, index+1);
+ var ch2 = this.ch + this.peek();
+ var ch3 = ch2 + this.peek(2);
+ var fn = OPERATORS[this.ch];
+ var fn2 = OPERATORS[ch2];
+ var fn3 = OPERATORS[ch3];
+ if (fn3) {
+ this.tokens.push({index: this.index, text: ch3, fn: fn3});
+ this.index += 3;
+ } else if (fn2) {
+ this.tokens.push({index: this.index, text: ch2, fn: fn2});
+ this.index += 2;
+ } else if (fn) {
+ this.tokens.push({
+ index: this.index,
+ text: this.ch,
+ fn: fn,
+ json: (this.was('[,:') && this.is('+-'))
+ });
+ this.index += 1;
+ } else {
+ this.throwError('Unexpected next character ', this.index, this.index + 1);
+ }
}
+ this.lastCh = this.ch;
}
- lastCh = ch;
- }
- return tokens;
+ return this.tokens;
+ },
- function is(chars) {
- return chars.indexOf(ch) != -1;
- }
+ is: function(chars) {
+ return chars.indexOf(this.ch) !== -1;
+ },
- function was(chars) {
- return chars.indexOf(lastCh) != -1;
- }
+ was: function(chars) {
+ return chars.indexOf(this.lastCh) !== -1;
+ },
- function peek(i) {
+ peek: function(i) {
var num = i || 1;
- return index + num < text.length ? text.charAt(index + num) : false;
- }
- function isNumber(ch) {
- return '0' <= ch && ch <= '9';
- }
- function isWhitespace(ch) {
- return ch == ' ' || ch == '\r' || ch == '\t' ||
- ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
- }
- function isIdent(ch) {
- return 'a' <= ch && ch <= 'z' ||
- 'A' <= ch && ch <= 'Z' ||
- '_' == ch || ch == '$';
- }
- function isExpOperator(ch) {
- return ch == '-' || ch == '+' || isNumber(ch);
- }
+ return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
+ },
- function throwError(error, start, end) {
- end = end || index;
- throw Error("Lexer Error: " + error + " at column" +
- (isDefined(start)
- ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
- : " " + end) +
- " in expression [" + text + "].");
- }
+ isNumber: function(ch) {
+ return ('0' <= ch && ch <= '9');
+ },
- function readNumber() {
- var number = "";
- var start = index;
- while (index < text.length) {
- var ch = lowercase(text.charAt(index));
- if (ch == '.' || isNumber(ch)) {
+ isWhitespace: function(ch) {
+ // IE treats non-breaking space as \u00A0
+ return (ch === ' ' || ch === '\r' || ch === '\t' ||
+ ch === '\n' || ch === '\v' || ch === '\u00A0');
+ },
+
+ isIdent: function(ch) {
+ return ('a' <= ch && ch <= 'z' ||
+ 'A' <= ch && ch <= 'Z' ||
+ '_' === ch || ch === '$');
+ },
+
+ isExpOperator: function(ch) {
+ return (ch === '-' || ch === '+' || this.isNumber(ch));
+ },
+
+ throwError: function(error, start, end) {
+ end = end || this.index;
+ var colStr = (isDefined(start)
+ ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
+ : ' ' + end);
+ throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
+ error, colStr, this.text);
+ },
+
+ readNumber: function() {
+ var number = '';
+ var start = this.index;
+ while (this.index < this.text.length) {
+ var ch = lowercase(this.text.charAt(this.index));
+ if (ch == '.' || this.isNumber(ch)) {
number += ch;
} else {
- var peekCh = peek();
- if (ch == 'e' && isExpOperator(peekCh)) {
+ var peekCh = this.peek();
+ if (ch == 'e' && this.isExpOperator(peekCh)) {
number += ch;
- } else if (isExpOperator(ch) &&
- peekCh && isNumber(peekCh) &&
+ } else if (this.isExpOperator(ch) &&
+ peekCh && this.isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
- } else if (isExpOperator(ch) &&
- (!peekCh || !isNumber(peekCh)) &&
+ } else if (this.isExpOperator(ch) &&
+ (!peekCh || !this.isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
- throwError('Invalid exponent');
+ this.throwError('Invalid exponent');
} else {
break;
}
}
- index++;
+ this.index++;
}
number = 1 * number;
- tokens.push({index:start, text:number, json:true,
- fn:function() {return number;}});
- }
- function readIdent() {
- var ident = "",
- start = index,
- lastDot, peekIndex, methodName;
+ this.tokens.push({
+ index: start,
+ text: number,
+ json: true,
+ fn: function() { return number; }
+ });
+ },
- while (index < text.length) {
- var ch = text.charAt(index);
- if (ch == '.' || isIdent(ch) || isNumber(ch)) {
- if (ch == '.') lastDot = index;
+ readIdent: function() {
+ var parser = this;
+
+ var ident = '';
+ var start = this.index;
+
+ var lastDot, peekIndex, methodName, ch;
+
+ while (this.index < this.text.length) {
+ ch = this.text.charAt(this.index);
+ if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
+ if (ch === '.') lastDot = this.index;
ident += ch;
} else {
break;
}
- index++;
+ this.index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
- peekIndex = index;
- while(peekIndex < text.length) {
- var ch = text.charAt(peekIndex);
- if (ch == '(') {
+ peekIndex = this.index;
+ while (peekIndex < this.text.length) {
+ ch = this.text.charAt(peekIndex);
+ if (ch === '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
- index = peekIndex;
+ this.index = peekIndex;
break;
}
- if(isWhitespace(ch)) {
+ if (this.isWhitespace(ch)) {
peekIndex++;
} else {
break;
@@ -6379,54 +9747,56 @@ function lex(text, csp){
var token = {
- index:start,
- text:ident
+ index: start,
+ text: ident
};
+ // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
if (OPERATORS.hasOwnProperty(ident)) {
- token.fn = token.json = OPERATORS[ident];
+ token.fn = OPERATORS[ident];
+ token.json = OPERATORS[ident];
} else {
- var getter = getterFn(ident, csp);
+ var getter = getterFn(ident, this.options, this.text);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
- return setter(self, ident, value);
+ return setter(self, ident, value, parser.text, parser.options);
}
});
}
- tokens.push(token);
+ this.tokens.push(token);
if (methodName) {
- tokens.push({
+ this.tokens.push({
index:lastDot,
text: '.',
json: false
});
- tokens.push({
+ this.tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
- }
+ },
- function readString(quote) {
- var start = index;
- index++;
- var string = "";
+ readString: function(quote) {
+ var start = this.index;
+ this.index++;
+ var string = '';
var rawString = quote;
var escape = false;
- while (index < text.length) {
- var ch = text.charAt(index);
+ while (this.index < this.text.length) {
+ var ch = this.text.charAt(this.index);
rawString += ch;
if (escape) {
- if (ch == 'u') {
- var hex = text.substring(index + 1, index + 5);
+ if (ch === 'u') {
+ var hex = this.text.substring(this.index + 1, this.index + 5);
if (!hex.match(/[\da-f]{4}/i))
- throwError( "Invalid unicode escape [\\u" + hex + "]");
- index += 4;
+ this.throwError('Invalid unicode escape [\\u' + hex + ']');
+ this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
@@ -6437,165 +9807,227 @@ function lex(text, csp){
}
}
escape = false;
- } else if (ch == '\\') {
+ } else if (ch === '\\') {
escape = true;
- } else if (ch == quote) {
- index++;
- tokens.push({
- index:start,
- text:rawString,
- string:string,
- json:true,
- fn:function() { return string; }
+ } else if (ch === quote) {
+ this.index++;
+ this.tokens.push({
+ index: start,
+ text: rawString,
+ string: string,
+ json: true,
+ fn: function() { return string; }
});
return;
} else {
string += ch;
}
- index++;
+ this.index++;
}
- throwError("Unterminated quote", start);
+ this.throwError('Unterminated quote', start);
}
-}
+};
-/////////////////////////////////////////
-function parser(text, json, $filter, csp){
- var ZERO = valueFn(0),
- value,
- tokens = lex(text, csp),
- assignment = _assignment,
- functionCall = _functionCall,
- fieldAccess = _fieldAccess,
- objectIndex = _objectIndex,
- filterChain = _filterChain;
+/**
+ * @constructor
+ */
+var Parser = function (lexer, $filter, options) {
+ this.lexer = lexer;
+ this.$filter = $filter;
+ this.options = options;
+};
- if(json){
- // The extra level of aliasing is here, just in case the lexer misses something, so that
- // we prevent any accidental execution in JSON.
- assignment = logicalOR;
- functionCall =
- fieldAccess =
- objectIndex =
- filterChain =
- function() { throwError("is not valid json", {text:text, index:0}); };
- value = primary();
- } else {
- value = statements();
- }
- if (tokens.length !== 0) {
- throwError("is an unexpected token", tokens[0]);
- }
- value.literal = !!value.literal;
- value.constant = !!value.constant;
- return value;
+Parser.ZERO = function () { return 0; };
- ///////////////////////////////////
- function throwError(msg, token) {
- throw Error("Syntax Error: Token '" + token.text +
- "' " + msg + " at column " +
- (token.index + 1) + " of the expression [" +
- text + "] starting at [" + text.substring(token.index) + "].");
- }
+Parser.prototype = {
+ constructor: Parser,
- function peekToken() {
- if (tokens.length === 0)
- throw Error("Unexpected end of expression: " + text);
- return tokens[0];
- }
+ parse: function (text, json) {
+ this.text = text;
- function peek(e1, e2, e3, e4) {
- if (tokens.length > 0) {
- var token = tokens[0];
+ //TODO(i): strip all the obsolte json stuff from this file
+ this.json = json;
+
+ this.tokens = this.lexer.lex(text);
+
+ if (json) {
+ // The extra level of aliasing is here, just in case the lexer misses something, so that
+ // we prevent any accidental execution in JSON.
+ this.assignment = this.logicalOR;
+
+ this.functionCall =
+ this.fieldAccess =
+ this.objectIndex =
+ this.filterChain = function() {
+ this.throwError('is not valid json', {text: text, index: 0});
+ };
+ }
+
+ var value = json ? this.primary() : this.statements();
+
+ if (this.tokens.length !== 0) {
+ this.throwError('is an unexpected token', this.tokens[0]);
+ }
+
+ value.literal = !!value.literal;
+ value.constant = !!value.constant;
+
+ return value;
+ },
+
+ primary: function () {
+ var primary;
+ if (this.expect('(')) {
+ primary = this.filterChain();
+ this.consume(')');
+ } else if (this.expect('[')) {
+ primary = this.arrayDeclaration();
+ } else if (this.expect('{')) {
+ primary = this.object();
+ } else {
+ var token = this.expect();
+ primary = token.fn;
+ if (!primary) {
+ this.throwError('not a primary expression', token);
+ }
+ if (token.json) {
+ primary.constant = true;
+ primary.literal = true;
+ }
+ }
+
+ var next, context;
+ while ((next = this.expect('(', '[', '.'))) {
+ if (next.text === '(') {
+ primary = this.functionCall(primary, context);
+ context = null;
+ } else if (next.text === '[') {
+ context = primary;
+ primary = this.objectIndex(primary);
+ } else if (next.text === '.') {
+ context = primary;
+ primary = this.fieldAccess(primary);
+ } else {
+ this.throwError('IMPOSSIBLE');
+ }
+ }
+ return primary;
+ },
+
+ throwError: function(msg, token) {
+ throw $parseMinErr('syntax',
+ 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
+ token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
+ },
+
+ peekToken: function() {
+ if (this.tokens.length === 0)
+ throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
+ return this.tokens[0];
+ },
+
+ peek: function(e1, e2, e3, e4) {
+ if (this.tokens.length > 0) {
+ var token = this.tokens[0];
var t = token.text;
- if (t==e1 || t==e2 || t==e3 || t==e4 ||
+ if (t === e1 || t === e2 || t === e3 || t === e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
- }
+ },
- function expect(e1, e2, e3, e4){
- var token = peek(e1, e2, e3, e4);
+ expect: function(e1, e2, e3, e4){
+ var token = this.peek(e1, e2, e3, e4);
if (token) {
- if (json && !token.json) {
- throwError("is not valid json", token);
+ if (this.json && !token.json) {
+ this.throwError('is not valid json', token);
}
- tokens.shift();
+ this.tokens.shift();
return token;
}
return false;
- }
+ },
- function consume(e1){
- if (!expect(e1)) {
- throwError("is unexpected, expecting [" + e1 + "]", peek());
+ consume: function(e1){
+ if (!this.expect(e1)) {
+ this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
}
- }
+ },
- function unaryFn(fn, right) {
+ unaryFn: function(fn, right) {
return extend(function(self, locals) {
return fn(self, locals, right);
}, {
constant:right.constant
});
- }
+ },
- function binaryFn(left, fn, right) {
+ ternaryFn: function(left, middle, right){
+ return extend(function(self, locals){
+ return left(self, locals) ? middle(self, locals) : right(self, locals);
+ }, {
+ constant: left.constant && middle.constant && right.constant
+ });
+ },
+
+ binaryFn: function(left, fn, right) {
return extend(function(self, locals) {
return fn(self, locals, left, right);
}, {
constant:left.constant && right.constant
});
- }
+ },
- function statements() {
+ statements: function() {
var statements = [];
- while(true) {
- if (tokens.length > 0 && !peek('}', ')', ';', ']'))
- statements.push(filterChain());
- if (!expect(';')) {
+ while (true) {
+ if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
+ statements.push(this.filterChain());
+ if (!this.expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
- return statements.length == 1
- ? statements[0]
- : function(self, locals){
- var value;
- for ( var i = 0; i < statements.length; i++) {
- var statement = statements[i];
- if (statement)
- value = statement(self, locals);
- }
- return value;
- };
+ return (statements.length === 1)
+ ? statements[0]
+ : function(self, locals) {
+ var value;
+ for (var i = 0; i < statements.length; i++) {
+ var statement = statements[i];
+ if (statement) {
+ value = statement(self, locals);
+ }
+ }
+ return value;
+ };
}
}
- }
+ },
- function _filterChain() {
- var left = expression();
+ filterChain: function() {
+ var left = this.expression();
var token;
- while(true) {
- if ((token = expect('|'))) {
- left = binaryFn(left, token.fn, filter());
+ while (true) {
+ if ((token = this.expect('|'))) {
+ left = this.binaryFn(left, token.fn, this.filter());
} else {
return left;
}
}
- }
+ },
- function filter() {
- var token = expect();
- var fn = $filter(token.text);
+ filter: function() {
+ var token = this.expect();
+ var fn = this.$filter(token.text);
var argsFn = [];
- while(true) {
- if ((token = expect(':'))) {
- argsFn.push(expression());
+ while (true) {
+ if ((token = this.expect(':'))) {
+ argsFn.push(this.expression());
} else {
- var fnInvoke = function(self, locals, input){
+ var fnInvoke = function(self, locals, input) {
var args = [input];
- for ( var i = 0; i < argsFn.length; i++) {
+ for (var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
@@ -6605,305 +10037,285 @@ function parser(text, json, $filter, csp){
};
}
}
- }
+ },
- function expression() {
- return assignment();
- }
+ expression: function() {
+ return this.assignment();
+ },
- function _assignment() {
- var left = logicalOR();
+ assignment: function() {
+ var left = this.ternary();
var right;
var token;
- if ((token = expect('='))) {
+ if ((token = this.expect('='))) {
if (!left.assign) {
- throwError("implies assignment but [" +
- text.substring(0, token.index) + "] can not be assigned to", token);
+ this.throwError('implies assignment but [' +
+ this.text.substring(0, token.index) + '] can not be assigned to', token);
}
- right = logicalOR();
- return function(self, locals){
- return left.assign(self, right(self, locals), locals);
+ right = this.ternary();
+ return function(scope, locals) {
+ return left.assign(scope, right(scope, locals), locals);
};
+ }
+ return left;
+ },
+
+ ternary: function() {
+ var left = this.logicalOR();
+ var middle;
+ var token;
+ if ((token = this.expect('?'))) {
+ middle = this.ternary();
+ if ((token = this.expect(':'))) {
+ return this.ternaryFn(left, middle, this.ternary());
+ } else {
+ this.throwError('expected :', token);
+ }
} else {
return left;
}
- }
+ },
- function logicalOR() {
- var left = logicalAND();
+ logicalOR: function() {
+ var left = this.logicalAND();
var token;
- while(true) {
- if ((token = expect('||'))) {
- left = binaryFn(left, token.fn, logicalAND());
+ while (true) {
+ if ((token = this.expect('||'))) {
+ left = this.binaryFn(left, token.fn, this.logicalAND());
} else {
return left;
}
}
- }
+ },
- function logicalAND() {
- var left = equality();
+ logicalAND: function() {
+ var left = this.equality();
var token;
- if ((token = expect('&&'))) {
- left = binaryFn(left, token.fn, logicalAND());
+ if ((token = this.expect('&&'))) {
+ left = this.binaryFn(left, token.fn, this.logicalAND());
}
return left;
- }
+ },
- function equality() {
- var left = relational();
+ equality: function() {
+ var left = this.relational();
var token;
- if ((token = expect('==','!=','===','!=='))) {
- left = binaryFn(left, token.fn, equality());
+ if ((token = this.expect('==','!=','===','!=='))) {
+ left = this.binaryFn(left, token.fn, this.equality());
}
return left;
- }
+ },
- function relational() {
- var left = additive();
+ relational: function() {
+ var left = this.additive();
var token;
- if ((token = expect('<', '>', '<=', '>='))) {
- left = binaryFn(left, token.fn, relational());
+ if ((token = this.expect('<', '>', '<=', '>='))) {
+ left = this.binaryFn(left, token.fn, this.relational());
}
return left;
- }
+ },
- function additive() {
- var left = multiplicative();
+ additive: function() {
+ var left = this.multiplicative();
var token;
- while ((token = expect('+','-'))) {
- left = binaryFn(left, token.fn, multiplicative());
+ while ((token = this.expect('+','-'))) {
+ left = this.binaryFn(left, token.fn, this.multiplicative());
}
return left;
- }
+ },
- function multiplicative() {
- var left = unary();
+ multiplicative: function() {
+ var left = this.unary();
var token;
- while ((token = expect('*','/','%'))) {
- left = binaryFn(left, token.fn, unary());
+ while ((token = this.expect('*','/','%'))) {
+ left = this.binaryFn(left, token.fn, this.unary());
}
return left;
- }
+ },
- function unary() {
+ unary: function() {
var token;
- if (expect('+')) {
- return primary();
- } else if ((token = expect('-'))) {
- return binaryFn(ZERO, token.fn, unary());
- } else if ((token = expect('!'))) {
- return unaryFn(token.fn, unary());
+ if (this.expect('+')) {
+ return this.primary();
+ } else if ((token = this.expect('-'))) {
+ return this.binaryFn(Parser.ZERO, token.fn, this.unary());
+ } else if ((token = this.expect('!'))) {
+ return this.unaryFn(token.fn, this.unary());
} else {
- return primary();
+ return this.primary();
}
- }
+ },
+ fieldAccess: function(object) {
+ var parser = this;
+ var field = this.expect().text;
+ var getter = getterFn(field, this.options, this.text);
- function primary() {
- var primary;
- if (expect('(')) {
- primary = filterChain();
- consume(')');
- } else if (expect('[')) {
- primary = arrayDeclaration();
- } else if (expect('{')) {
- primary = object();
- } else {
- var token = expect();
- primary = token.fn;
- if (!primary) {
- throwError("not a primary expression", token);
+ return extend(function(scope, locals, self) {
+ return getter(self || object(scope, locals));
+ }, {
+ assign: function(scope, value, locals) {
+ return setter(object(scope, locals), field, value, parser.text, parser.options);
}
- if (token.json) {
- primary.constant = primary.literal = true;
+ });
+ },
+
+ objectIndex: function(obj) {
+ var parser = this;
+
+ var indexFn = this.expression();
+ this.consume(']');
+
+ return extend(function(self, locals) {
+ var o = obj(self, locals),
+ i = indexFn(self, locals),
+ v, p;
+
+ if (!o) return undefined;
+ v = ensureSafeObject(o[i], parser.text);
+ if (v && v.then && parser.options.unwrapPromises) {
+ p = v;
+ if (!('$$v' in v)) {
+ p.$$v = undefined;
+ p.then(function(val) { p.$$v = val; });
+ }
+ v = v.$$v;
}
- }
-
- var next, context;
- while ((next = expect('(', '[', '.'))) {
- if (next.text === '(') {
- primary = functionCall(primary, context);
- context = null;
- } else if (next.text === '[') {
- context = primary;
- primary = objectIndex(primary);
- } else if (next.text === '.') {
- context = primary;
- primary = fieldAccess(primary);
- } else {
- throwError("IMPOSSIBLE");
+ return v;
+ }, {
+ assign: function(self, value, locals) {
+ var key = indexFn(self, locals);
+ // prevent overwriting of Function.constructor which would break ensureSafeObject check
+ var safe = ensureSafeObject(obj(self, locals), parser.text);
+ return safe[key] = value;
}
- }
- return primary;
- }
+ });
+ },
- function _fieldAccess(object) {
- var field = expect().text;
- var getter = getterFn(field, csp);
- return extend(
- function(self, locals) {
- return getter(object(self, locals), locals);
- },
- {
- assign:function(self, value, locals) {
- return setter(object(self, locals), field, value);
- }
- }
- );
- }
-
- function _objectIndex(obj) {
- var indexFn = expression();
- consume(']');
- return extend(
- function(self, locals){
- var o = obj(self, locals),
- i = indexFn(self, locals),
- v, p;
-
- if (!o) return undefined;
- v = o[i];
- if (v && v.then) {
- p = v;
- if (!('$$v' in v)) {
- p.$$v = undefined;
- p.then(function(val) { p.$$v = val; });
- }
- v = v.$$v;
- }
- return v;
- }, {
- assign:function(self, value, locals){
- return obj(self, locals)[indexFn(self, locals)] = value;
- }
- });
- }
-
- function _functionCall(fn, contextGetter) {
+ functionCall: function(fn, contextGetter) {
var argsFn = [];
- if (peekToken().text != ')') {
+ if (this.peekToken().text !== ')') {
do {
- argsFn.push(expression());
- } while (expect(','));
+ argsFn.push(this.expression());
+ } while (this.expect(','));
}
- consume(')');
- return function(self, locals){
- var args = [],
- context = contextGetter ? contextGetter(self, locals) : self;
+ this.consume(')');
- for ( var i = 0; i < argsFn.length; i++) {
- args.push(argsFn[i](self, locals));
+ var parser = this;
+
+ return function(scope, locals) {
+ var args = [];
+ var context = contextGetter ? contextGetter(scope, locals) : scope;
+
+ for (var i = 0; i < argsFn.length; i++) {
+ args.push(argsFn[i](scope, locals));
}
- var fnPtr = fn(self, locals) || noop;
- // IE stupidity!
- return fnPtr.apply
- ? fnPtr.apply(context, args)
- : fnPtr(args[0], args[1], args[2], args[3], args[4]);
+ var fnPtr = fn(scope, locals, context) || noop;
+
+ ensureSafeObject(context, parser.text);
+ ensureSafeObject(fnPtr, parser.text);
+
+ // IE stupidity! (IE doesn't have apply for some native functions)
+ var v = fnPtr.apply
+ ? fnPtr.apply(context, args)
+ : fnPtr(args[0], args[1], args[2], args[3], args[4]);
+
+ return ensureSafeObject(v, parser.text);
};
- }
+ },
// This is used with json array declaration
- function arrayDeclaration () {
+ arrayDeclaration: function () {
var elementFns = [];
var allConstant = true;
- if (peekToken().text != ']') {
+ if (this.peekToken().text !== ']') {
do {
- var elementFn = expression();
+ var elementFn = this.expression();
elementFns.push(elementFn);
if (!elementFn.constant) {
allConstant = false;
}
- } while (expect(','));
+ } while (this.expect(','));
}
- consume(']');
- return extend(function(self, locals){
+ this.consume(']');
+
+ return extend(function(self, locals) {
var array = [];
- for ( var i = 0; i < elementFns.length; i++) {
+ for (var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
}, {
- literal:true,
- constant:allConstant
+ literal: true,
+ constant: allConstant
});
- }
+ },
- function object () {
+ object: function () {
var keyValues = [];
var allConstant = true;
- if (peekToken().text != '}') {
+ if (this.peekToken().text !== '}') {
do {
- var token = expect(),
+ var token = this.expect(),
key = token.string || token.text;
- consume(":");
- var value = expression();
- keyValues.push({key:key, value:value});
+ this.consume(':');
+ var value = this.expression();
+ keyValues.push({key: key, value: value});
if (!value.constant) {
allConstant = false;
}
- } while (expect(','));
+ } while (this.expect(','));
}
- consume('}');
- return extend(function(self, locals){
+ this.consume('}');
+
+ return extend(function(self, locals) {
var object = {};
- for ( var i = 0; i < keyValues.length; i++) {
+ for (var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
- var value = keyValue.value(self, locals);
- object[keyValue.key] = value;
+ object[keyValue.key] = keyValue.value(self, locals);
}
return object;
}, {
- literal:true,
- constant:allConstant
+ literal: true,
+ constant: allConstant
});
}
-}
+};
+
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
-function setter(obj, path, setValue) {
- var element = path.split('.');
+function setter(obj, path, setValue, fullExp, options) {
+ //needed?
+ options = options || {};
+
+ var element = path.split('.'), key;
for (var i = 0; element.length > 1; i++) {
- var key = element.shift();
+ key = ensureSafeMemberName(element.shift(), fullExp);
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
- }
- obj[element.shift()] = setValue;
- return setValue;
-}
-
-/**
- * Return the value accessible from the object by path. Any undefined traversals are ignored
- * @param {Object} obj starting object
- * @param {string} path path to traverse
- * @param {boolean=true} bindFnToScope
- * @returns value as accessible by path
- */
-//TODO(misko): this function needs to be removed
-function getter(obj, path, bindFnToScope) {
- if (!path) return obj;
- var keys = path.split('.');
- var key;
- var lastInstance = obj;
- var len = keys.length;
-
- for (var i = 0; i < len; i++) {
- key = keys[i];
- if (obj) {
- obj = (lastInstance = obj)[key];
+ if (obj.then && options.unwrapPromises) {
+ promiseWarning(fullExp);
+ if (!("$$v" in obj)) {
+ (function(promise) {
+ promise.then(function(val) { promise.$$v = val; }); }
+ )(obj);
+ }
+ if (obj.$$v === undefined) {
+ obj.$$v = {};
+ }
+ obj = obj.$$v;
}
}
- if (!bindFnToScope && isFunction(obj)) {
- return bind(lastInstance, obj);
- }
- return obj;
+ key = ensureSafeMemberName(element.shift(), fullExp);
+ obj[key] = setValue;
+ return setValue;
}
var getterFnCache = {};
@@ -6913,71 +10325,134 @@ var getterFnCache = {};
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
-function cspSafeGetterFn(key0, key1, key2, key3, key4) {
- return function(scope, locals) {
- var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
- promise;
+function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
+ ensureSafeMemberName(key0, fullExp);
+ ensureSafeMemberName(key1, fullExp);
+ ensureSafeMemberName(key2, fullExp);
+ ensureSafeMemberName(key3, fullExp);
+ ensureSafeMemberName(key4, fullExp);
- if (pathVal === null || pathVal === undefined) return pathVal;
+ return !options.unwrapPromises
+ ? function cspSafeGetter(scope, locals) {
+ var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
- pathVal = pathVal[key0];
- if (pathVal && pathVal.then) {
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
- if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
+ if (pathVal == null) return pathVal;
+ pathVal = pathVal[key0];
- pathVal = pathVal[key1];
- if (pathVal && pathVal.then) {
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
- if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
+ if (!key1) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key1];
- pathVal = pathVal[key2];
- if (pathVal && pathVal.then) {
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
- if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
+ if (!key2) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key2];
- pathVal = pathVal[key3];
- if (pathVal && pathVal.then) {
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
- if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
+ if (!key3) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key3];
- pathVal = pathVal[key4];
- if (pathVal && pathVal.then) {
- if (!("$$v" in pathVal)) {
- promise = pathVal;
- promise.$$v = undefined;
- promise.then(function(val) { promise.$$v = val; });
- }
- pathVal = pathVal.$$v;
- }
- return pathVal;
+ if (!key4) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key4];
+
+ return pathVal;
+ }
+ : function cspSafePromiseEnabledGetter(scope, locals) {
+ var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
+ promise;
+
+ if (pathVal == null) return pathVal;
+
+ pathVal = pathVal[key0];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key1) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key1];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key2) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key2];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key3) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key3];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+
+ if (!key4) return pathVal;
+ if (pathVal == null) return undefined;
+ pathVal = pathVal[key4];
+ if (pathVal && pathVal.then) {
+ promiseWarning(fullExp);
+ if (!("$$v" in pathVal)) {
+ promise = pathVal;
+ promise.$$v = undefined;
+ promise.then(function(val) { promise.$$v = val; });
+ }
+ pathVal = pathVal.$$v;
+ }
+ return pathVal;
+ };
+}
+
+function simpleGetterFn1(key0, fullExp) {
+ ensureSafeMemberName(key0, fullExp);
+
+ return function simpleGetterFn1(scope, locals) {
+ if (scope == null) return undefined;
+ return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
};
-};
+}
-function getterFn(path, csp) {
+function simpleGetterFn2(key0, key1, fullExp) {
+ ensureSafeMemberName(key0, fullExp);
+ ensureSafeMemberName(key1, fullExp);
+
+ return function simpleGetterFn2(scope, locals) {
+ if (scope == null) return undefined;
+ scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
+ return scope == null ? undefined : scope[key1];
+ };
+}
+
+function getterFn(path, options, fullExp) {
+ // Check whether the cache has this getter already.
+ // We can use hasOwnProperty directly on the cache because we ensure,
+ // see below, that the cache never stores a path called 'hasOwnProperty'
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
@@ -6986,46 +10461,68 @@ function getterFn(path, csp) {
pathKeysLength = pathKeys.length,
fn;
- if (csp) {
- fn = (pathKeysLength < 6)
- ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
- : function(scope, locals) {
- var i = 0, val
- do {
- val = cspSafeGetterFn(
- pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
- )(scope, locals);
+ // When we have only 1 or 2 tokens, use optimized special case closures.
+ // http://jsperf.com/angularjs-parse-getter/6
+ if (!options.unwrapPromises && pathKeysLength === 1) {
+ fn = simpleGetterFn1(pathKeys[0], fullExp);
+ } else if (!options.unwrapPromises && pathKeysLength === 2) {
+ fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp);
+ } else if (options.csp) {
+ if (pathKeysLength < 6) {
+ fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
+ options);
+ } else {
+ fn = function(scope, locals) {
+ var i = 0, val;
+ do {
+ val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
+ pathKeys[i++], fullExp, options)(scope, locals);
- locals = undefined; // clear after first iteration
- scope = val;
- } while (i < pathKeysLength);
- return val;
- }
+ locals = undefined; // clear after first iteration
+ scope = val;
+ } while (i < pathKeysLength);
+ return val;
+ };
+ }
} else {
- var code = 'var l, fn, p;\n';
+ var code = 'var p;\n';
forEach(pathKeys, function(key, index) {
- code += 'if(s === null || s === undefined) return s;\n' +
- 'l=s;\n' +
+ ensureSafeMemberName(key, fullExp);
+ code += 'if(s == null) return undefined;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
- 'if (s && s.then) {\n' +
- ' if (!("$$v" in s)) {\n' +
- ' p=s;\n' +
- ' p.$$v = undefined;\n' +
- ' p.then(function(v) {p.$$v=v;});\n' +
- '}\n' +
- ' s=s.$$v\n' +
- '}\n';
+ (options.unwrapPromises
+ ? 'if (s && s.then) {\n' +
+ ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
+ ' if (!("$$v" in s)) {\n' +
+ ' p=s;\n' +
+ ' p.$$v = undefined;\n' +
+ ' p.then(function(v) {p.$$v=v;});\n' +
+ '}\n' +
+ ' s=s.$$v\n' +
+ '}\n'
+ : '');
});
code += 'return s;';
- fn = Function('s', 'k', code); // s=scope, k=locals
- fn.toString = function() { return code; };
+
+ /* jshint -W054 */
+ var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
+ /* jshint +W054 */
+ evaledFnGetter.toString = valueFn(code);
+ fn = options.unwrapPromises ? function(scope, locals) {
+ return evaledFnGetter(scope, locals, promiseWarning);
+ } : evaledFnGetter;
}
- return getterFnCache[path] = fn;
+ // Only cache the value if it's not going to mess up the cache object
+ // This is more performant that using Object.prototype.hasOwnProperty.call
+ if (path !== 'hasOwnProperty') {
+ getterFnCache[path] = fn;
+ }
+ return fn;
}
///////////////////////////////////
@@ -7069,17 +10566,145 @@ function getterFn(path, csp) {
* set to a function to change its value on the given context.
*
*/
+
+
+/**
+ * @ngdoc object
+ * @name ng.$parseProvider
+ * @function
+ *
+ * @description
+ * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
+ * service.
+ */
function $ParseProvider() {
var cache = {};
- this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
+
+ var $parseOptions = {
+ csp: false,
+ unwrapPromises: false,
+ logPromiseWarnings: true
+ };
+
+
+ /**
+ * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
+ *
+ * @ngdoc method
+ * @name ng.$parseProvider#unwrapPromises
+ * @methodOf ng.$parseProvider
+ * @description
+ *
+ * **This feature is deprecated, see deprecation notes below for more info**
+ *
+ * If set to true (default is false), $parse will unwrap promises automatically when a promise is
+ * found at any part of the expression. In other words, if set to true, the expression will always
+ * result in a non-promise value.
+ *
+ * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
+ * the fulfillment value is used in place of the promise while evaluating the expression.
+ *
+ * **Deprecation notice**
+ *
+ * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
+ * dichotomy between data access in templates (accessed as raw values) and controller code
+ * (accessed as promises).
+ *
+ * In most code we ended up resolving promises manually in controllers anyway and thus unifying
+ * the model access there.
+ *
+ * Other downsides of automatic promise unwrapping:
+ *
+ * - when building components it's often desirable to receive the raw promises
+ * - adds complexity and slows down expression evaluation
+ * - makes expression code pre-generation unattractive due to the amount of code that needs to be
+ * generated
+ * - makes IDE auto-completion and tool support hard
+ *
+ * **Warning Logs**
+ *
+ * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
+ * promise (to reduce the noise, each expression is logged only once). To disable this logging use
+ * `$parseProvider.logPromiseWarnings(false)` api.
+ *
+ *
+ * @param {boolean=} value New value.
+ * @returns {boolean|self} Returns the current setting when used as getter and self if used as
+ * setter.
+ */
+ this.unwrapPromises = function(value) {
+ if (isDefined(value)) {
+ $parseOptions.unwrapPromises = !!value;
+ return this;
+ } else {
+ return $parseOptions.unwrapPromises;
+ }
+ };
+
+
+ /**
+ * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
+ *
+ * @ngdoc method
+ * @name ng.$parseProvider#logPromiseWarnings
+ * @methodOf ng.$parseProvider
+ * @description
+ *
+ * Controls whether Angular should log a warning on any encounter of a promise in an expression.
+ *
+ * The default is set to `true`.
+ *
+ * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
+ *
+ * @param {boolean=} value New value.
+ * @returns {boolean|self} Returns the current setting when used as getter and self if used as
+ * setter.
+ */
+ this.logPromiseWarnings = function(value) {
+ if (isDefined(value)) {
+ $parseOptions.logPromiseWarnings = value;
+ return this;
+ } else {
+ return $parseOptions.logPromiseWarnings;
+ }
+ };
+
+
+ this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
+ $parseOptions.csp = $sniffer.csp;
+
+ promiseWarning = function promiseWarningFn(fullExp) {
+ if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
+ promiseWarningCache[fullExp] = true;
+ $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
+ 'Automatic unwrapping of promises in Angular expressions is deprecated.');
+ };
+
return function(exp) {
- switch(typeof exp) {
+ var parsedExpression;
+
+ switch (typeof exp) {
case 'string':
- return cache.hasOwnProperty(exp)
- ? cache[exp]
- : cache[exp] = parser(exp, false, $filter, $sniffer.csp);
+
+ if (cache.hasOwnProperty(exp)) {
+ return cache[exp];
+ }
+
+ var lexer = new Lexer($parseOptions);
+ var parser = new Parser(lexer, $filter, $parseOptions);
+ parsedExpression = parser.parse(exp, false);
+
+ if (exp !== 'hasOwnProperty') {
+ // Only cache the value if it's not going to mess up the cache object
+ // This is more performant that using Object.prototype.hasOwnProperty.call
+ cache[exp] = parsedExpression;
+ }
+
+ return parsedExpression;
+
case 'function':
return exp;
+
default:
return noop;
}
@@ -7103,9 +10728,9 @@ function $ParseProvider() {
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
*
- * // for the purpose of this example let's assume that variables `$q` and `scope` are
- * // available in the current lexical scope (they could have been injected or passed in).
- *
+ * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
+ * // are available in the current lexical scope (they could have been injected or passed in).
+ *
* function asyncGreet(name) {
* var deferred = $q.defer();
*
@@ -7113,6 +10738,8 @@ function $ParseProvider() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
+ * deferred.notify('About to greet ' + name + '.');
+ *
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
@@ -7129,12 +10756,14 @@ function $ParseProvider() {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
+ * }, function(update) {
+ * alert('Got notification: ' + update);
* });
*
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
- * comes in the way of
- * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
+ * comes in the way of guarantees that promise and deferred APIs make, see
+ * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
@@ -7147,7 +10776,8 @@ function $ParseProvider() {
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
- * that can be used for signaling the successful or unsuccessful completion of the task.
+ * that can be used for signaling the successful or unsuccessful completion, as well as the status
+ * of the task.
*
* **Methods**
*
@@ -7155,6 +10785,8 @@ function $ParseProvider() {
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
+ * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
+ * multiple times before the promise is either resolved or rejected.
*
* **Properties**
*
@@ -7171,68 +10803,81 @@ function $ParseProvider() {
*
* **Methods**
*
- * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
- * or rejected calls one of the success or error callbacks asynchronously as soon as the result
- * is available. The callbacks are called with a single argument the result or rejection reason.
+ * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
+ * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
+ * as soon as the result is available. The callbacks are called with a single argument: the result
+ * or rejection reason. Additionally, the notify callback may be called zero or more times to
+ * provide a progress indication, before the promise is resolved or rejected.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
- * `successCallback` or `errorCallback`.
+ * `successCallback`, `errorCallback`. It also notifies via the return value of the
+ * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
+ * method.
*
+ * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
+ *
+ * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
+ * but to do so without modifying the final value. This is useful to release resources or do some
+ * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
+ * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
+ * more information.
+ *
+ * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
+ * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
+ * make your code IE8 compatible.
*
* # Chaining promises
*
- * Because calling `then` api of a promise returns a new derived promise, it is easily possible
- * to create a chain of promises:
+ * Because calling the `then` method of a promise returns a new derived promise, it is easily
+ * possible to create a chain of promises:
*
*
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
- * // promiseB will be resolved immediately after promiseA is resolved and its value will be
- * // the result of promiseA incremented by 1
+ * // promiseB will be resolved immediately after promiseA is resolved and its value
+ * // will be the result of promiseA incremented by 1
*
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
- * the promises at any point in the chain. This makes it possible to implement powerful apis like
+ * the promises at any point in the chain. This makes it possible to implement powerful APIs like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
- * There are three main differences:
+ * There are two main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
- * - $q promises are recognized by the templating engine in angular, which means that in templates
- * you can treat promises attached to a scope as if they were the resulting values.
- * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
+ * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
- *
+ *
* # Testing
- *
+ *
*
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
- *
+ *
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
- *
+ *
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
- *
+ *
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
- * });
+ * }));
*
*/
function $QProvider() {
@@ -7281,7 +10926,7 @@ function qFactory(nextTick, exceptionHandler) {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
- value.then(callback[0], callback[1]);
+ value.then(callback[0], callback[1], callback[2]);
}
});
}
@@ -7290,39 +10935,105 @@ function qFactory(nextTick, exceptionHandler) {
reject: function(reason) {
- deferred.resolve(reject(reason));
+ deferred.resolve(createInternalRejectedPromise(reason));
+ },
+
+
+ notify: function(progress) {
+ if (pending) {
+ var callbacks = pending;
+
+ if (pending.length) {
+ nextTick(function() {
+ var callback;
+ for (var i = 0, ii = callbacks.length; i < ii; i++) {
+ callback = callbacks[i];
+ callback[2](progress);
+ }
+ });
+ }
+ }
},
promise: {
- then: function(callback, errback) {
+ then: function(callback, errback, progressback) {
var result = defer();
var wrappedCallback = function(value) {
try {
- result.resolve((callback || defaultCallback)(value));
+ result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
} catch(e) {
- exceptionHandler(e);
result.reject(e);
+ exceptionHandler(e);
}
};
var wrappedErrback = function(reason) {
try {
- result.resolve((errback || defaultErrback)(reason));
+ result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
+ } catch(e) {
+ result.reject(e);
+ exceptionHandler(e);
+ }
+ };
+
+ var wrappedProgressback = function(progress) {
+ try {
+ result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
} catch(e) {
exceptionHandler(e);
- result.reject(e);
}
};
if (pending) {
- pending.push([wrappedCallback, wrappedErrback]);
+ pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
} else {
- value.then(wrappedCallback, wrappedErrback);
+ value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
}
return result.promise;
+ },
+
+ "catch": function(callback) {
+ return this.then(null, callback);
+ },
+
+ "finally": function(callback) {
+
+ function makePromise(value, resolved) {
+ var result = defer();
+ if (resolved) {
+ result.resolve(value);
+ } else {
+ result.reject(value);
+ }
+ return result.promise;
+ }
+
+ function handleCallback(value, isResolved) {
+ var callbackOutput = null;
+ try {
+ callbackOutput = (callback ||defaultCallback)();
+ } catch(e) {
+ return makePromise(e, false);
+ }
+ if (callbackOutput && isFunction(callbackOutput.then)) {
+ return callbackOutput.then(function() {
+ return makePromise(value, isResolved);
+ }, function(error) {
+ return makePromise(error, false);
+ });
+ } else {
+ return makePromise(value, isResolved);
+ }
+ }
+
+ return this.then(function(value) {
+ return handleCallback(value, true);
+ }, function(error) {
+ return handleCallback(error, false);
+ });
}
}
};
@@ -7332,7 +11043,7 @@ function qFactory(nextTick, exceptionHandler) {
var ref = function(value) {
- if (value && value.then) return value;
+ if (value && isFunction(value.then)) return value;
return {
then: function(callback) {
var result = defer();
@@ -7381,11 +11092,22 @@ function qFactory(nextTick, exceptionHandler) {
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
+ var result = defer();
+ result.reject(reason);
+ return result.promise;
+ };
+
+ var createInternalRejectedPromise = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
- result.resolve((errback || defaultErrback)(reason));
+ try {
+ result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
+ } catch(e) {
+ result.reject(e);
+ exceptionHandler(e);
+ }
});
return result.promise;
}
@@ -7403,18 +11125,15 @@ function qFactory(nextTick, exceptionHandler) {
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
- * @returns {Promise} Returns a single promise that will be resolved with an array of values,
- * each value corresponding to the promise at the same index in the `promises` array. If any of
- * the promises is resolved with a rejection, this resulting promise will be resolved with the
- * same rejection.
+ * @returns {Promise} Returns a promise of the passed value or promise
*/
- var when = function(value, callback, errback) {
+ var when = function(value, callback, errback, progressback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
- return (callback || defaultCallback)(value);
+ return (isFunction(callback) ? callback : defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
@@ -7423,22 +11142,33 @@ function qFactory(nextTick, exceptionHandler) {
var wrappedErrback = function(reason) {
try {
- return (errback || defaultErrback)(reason);
+ return (isFunction(errback) ? errback : defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
+ var wrappedProgressback = function(progress) {
+ try {
+ return (isFunction(progressback) ? progressback : defaultCallback)(progress);
+ } catch (e) {
+ exceptionHandler(e);
+ }
+ };
+
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
- result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
+ result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
+ }, function(progress) {
+ if (done) return;
+ result.notify(wrappedProgressback(progress));
});
});
@@ -7466,9 +11196,9 @@ function qFactory(nextTick, exceptionHandler) {
*
* @param {Array.|Object.} promises An array or hash of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
- * each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of
- * the promises is resolved with a rejection, this resulting promise will be resolved with the
- * same rejection.
+ * each value corresponding to the promise at the same index/key in the `promises` array/hash.
+ * If any of the promises is resolved with a rejection, this resulting promise will be rejected
+ * with the same rejection value.
*/
function all(promises) {
var deferred = defer(),
@@ -7502,559 +11232,25 @@ function qFactory(nextTick, exceptionHandler) {
};
}
-/**
- * @ngdoc object
- * @name ng.$routeProvider
- * @function
- *
- * @description
- *
- * Used for configuring routes. See {@link ng.$route $route} for an example.
- */
-function $RouteProvider(){
- var routes = {};
-
- /**
- * @ngdoc method
- * @name ng.$routeProvider#when
- * @methodOf ng.$routeProvider
- *
- * @param {string} path Route path (matched against `$location.path`). If `$location.path`
- * contains redundant trailing slash or is missing one, the route will still match and the
- * `$location.path` will be updated to add or drop the trailing slash to exactly match the
- * route definition.
- *
- * * `path` can contain named groups starting with a colon (`:name`). All characters up
- * to the next slash are matched and stored in `$routeParams` under the given `name`
- * when the route matches.
- * * `path` can contain named groups starting with a star (`*name`). All characters are
- * eagerly stored in `$routeParams` under the given `name` when the route matches.
- *
- * For example, routes like `/color/:color/largecode/*largecode/edit` will match
- * `/color/brown/largecode/code/with/slashs/edit` and extract:
- *
- * * `color: brown`
- * * `largecode: code/with/slashs`.
- *
- *
- * @param {Object} route Mapping information to be assigned to `$route.current` on route
- * match.
- *
- * Object properties:
- *
- * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly
- * created scope or the name of a {@link angular.Module#controller registered controller}
- * if passed as a string.
- * - `template` – `{string=|function()=}` – html template as a string or function that returns
- * an html template as a string which should be used by {@link ng.directive:ngView ngView} or
- * {@link ng.directive:ngInclude ngInclude} directives.
- * This property takes precedence over `templateUrl`.
- *
- * If `template` is a function, it will be called with the following parameters:
- *
- * - `{Array.
-
+
it('should check ng-class-odd and ng-class-even', function() {
- expect(element('.doc-example-live li:first span').prop('className')).
+ expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
- expect(element('.doc-example-live li:last span').prop('className')).
+ expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
@@ -13691,13 +17602,14 @@ var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
+ * @restrict AC
*
* @description
- * The `ngClassOdd` and `ngClassEven` works exactly as
- * {@link ng.directive:ngClass ngClass}, except it works in
- * conjunction with `ngRepeat` and takes affect only on odd (even) rows.
+ * The `ngClassOdd` and `ngClassEven` directives work exactly as
+ * {@link ng.directive:ngClass ngClass}, except they work in
+ * conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
- * This directive can be applied only within a scope of an
+ * This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
@@ -13723,11 +17635,11 @@ var ngClassOddDirective = classDirective('Odd', 0);
color: blue;
}
-
+
it('should check ng-class-odd and ng-class-even', function() {
- expect(element('.doc-example-live li:first span').prop('className')).
+ expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
- expect(element('.doc-example-live li:last span').prop('className')).
+ expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
@@ -13738,36 +17650,39 @@ var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
+ * @restrict AC
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
- * The directive can be applied to the `` element, but typically a fine-grained application is
- * preferred in order to benefit from progressive rendering of the browser view.
+ * The directive can be applied to the `` element, but the preferred usage is to apply
+ * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
+ * of the browser view.
*
- * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
- * `angular.min.js` files. Following is the css rule:
+ * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
+ * `angular.min.js`.
+ * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
*
*
* When this css rule is loaded by the browser, all html elements (including their children) that
- * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
- * during the compilation of the template it deletes the `ngCloak` element attribute, which
- * makes the compiled element visible.
+ * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
+ * during the compilation of the template it deletes the `ngCloak` element attribute, making
+ * the compiled element visible.
*
- * For the best result, `angular.js` script must be loaded in the head section of the html file;
- * alternatively, the css rule (above) must be included in the external stylesheet of the
+ * For the best result, the `angular.js` script must be loaded in the head section of the html
+ * document; alternatively, the css rule above must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
- * class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
+ * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
*
* @element ANY
*
@@ -13777,14 +17692,14 @@ var ngClassEvenDirective = classDirective('Even', 1);
{{ 'hello' }}
{{ 'hello IE7' }}
-
+
it('should remove the template directive and css class', function() {
- expect(element('.doc-example-live #template1').attr('ng-cloak')).
- not().toBeDefined();
- expect(element('.doc-example-live #template2').attr('ng-cloak')).
- not().toBeDefined();
+ expect($('.doc-example-live #template1').getAttribute('ng-cloak')).
+ toBeNull();
+ expect($('.doc-example-live #template2').getAttribute('ng-cloak')).
+ toBeNull();
});
-
+
*
*/
@@ -13800,24 +17715,28 @@ var ngCloakDirective = ngDirective({
* @name ng.directive:ngController
*
* @description
- * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
+ * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
- * * Model — The Model is data in scope properties; scopes are attached to the DOM.
- * * View — The template (HTML with data bindings) is rendered into the View.
- * * Controller — The `ngController` directive specifies a Controller class; the class has
- * methods that typically express the business logic behind the application.
+ * * Model — The Model is scope properties; scopes are attached to the DOM where scope properties
+ * are accessed through bindings.
+ * * View — The template (HTML with data bindings) that is rendered into the View.
+ * * Controller — The `ngController` directive specifies a Controller class; the class contains business
+ * logic behind the application to decorate the scope with functions and values
*
- * Note that an alternative way to define controllers is via the `{@link ng.$route}`
- * service.
+ * Note that you can also attach controllers to the DOM by declaring it in a route definition
+ * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
+ * again using `ng-controller` in the template itself. This will cause the controller to be attached
+ * and executed twice.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
- * constructor function.
+ * constructor function. The controller instance can be published into a scope property
+ * by specifying `as propertyName`.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
@@ -13825,11 +17744,89 @@ var ngCloakDirective = ngDirective({
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
- * for a manual update.
+ * for a manual update. The example is shown in two different declaration styles you may use
+ * according to preference.
+
-
+
it('should check controller', function() {
- expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
- expect(element('.doc-example-live li:nth-child(1) input').val())
- .toBe('408 555 1212');
- expect(element('.doc-example-live li:nth-child(2) input').val())
- .toBe('john.smith@example.org');
+ var container = element(by.id('ctrl-exmpl'));
- element('.doc-example-live li:first a:contains("clear")').click();
- expect(element('.doc-example-live li:first input').val()).toBe('');
+ expect(container.findElement(by.model('name'))
+ .getAttribute('value')).toBe('John Smith');
- element('.doc-example-live li:last a:contains("add")').click();
- expect(element('.doc-example-live li:nth-child(3) input').val())
- .toBe('yourname@example.org');
+ var firstRepeat =
+ container.findElement(by.repeater('contact in contacts').row(0));
+ var secondRepeat =
+ container.findElement(by.repeater('contact in contacts').row(1));
+
+ expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ .toBe('408 555 1212');
+ expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ .toBe('john.smith@example.org');
+
+ firstRepeat.findElement(by.linkText('clear')).click()
+
+ expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ .toBe('');
+
+ container.findElement(by.linkText('add')).click();
+
+ expect(container.findElement(by.repeater('contact in contacts').row(2))
+ .findElement(by.model('contact.value'))
+ .getAttribute('value'))
+ .toBe('yourname@example.org');
});
-
+
+
*/
var ngControllerDirective = [function() {
return {
scope: true,
- controller: '@'
+ controller: '@',
+ priority: 500
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
- * @priority 1000
- *
- * @description
- * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
- * This directive should be used on the root element of the application (typically the ``
- * element or other element with the {@link ng.directive:ngApp ngApp}
- * directive).
- *
- * If enabled the performance of template expression evaluator will suffer slightly, so don't enable
- * this mode unless you need it.
*
* @element html
+ * @description
+ * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
+ *
+ * This is necessary when developing things like Google Chrome Extensions.
+ *
+ * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
+ * For us to be compatible, we just need to implement the "getterFn" in $parse without violating
+ * any of these restrictions.
+ *
+ * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
+ * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
+ * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
+ * be raised.
+ *
+ * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
+ * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
+ * To make those directives work in CSP mode, include the `angular-csp.css` manually.
+ *
+ * In order to use this feature put the `ngCsp` directive on the root element of the application.
+ *
+ * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
+ *
+ * @example
+ * This example shows how to apply the `ngCsp` directive to the `html` tag.
+
+
+
+ ...
+ ...
+
+
*/
-var ngCspDirective = ['$sniffer', function($sniffer) {
- return {
- priority: 1000,
- compile: function() {
- $sniffer.csp = true;
- }
- };
-}];
+// ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap
+// the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute
+// anywhere in the current doc
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
- * The ngClick allows you to specify custom behavior when
- * element is clicked.
+ * The ngClick directive allows you to specify custom behavior when
+ * an element is clicked.
*
* @element ANY
+ * @priority 0
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
@@ -13943,13 +17973,13 @@ var ngCspDirective = ['$sniffer', function($sniffer) {
count: {{count}}
-
+
it('should check ng-click', function() {
- expect(binding('count')).toBe('0');
- element('.doc-example-live :button').click();
- expect(binding('count')).toBe('1');
+ expect(element(by.binding('count')).getText()).toMatch('0');
+ element(by.css('.doc-example-live button')).click();
+ expect(element(by.binding('count')).getText()).toMatch('1');
});
-
+
*/
/*
@@ -13960,17 +17990,21 @@ var ngCspDirective = ['$sniffer', function($sniffer) {
*/
var ngEventDirectives = {};
forEach(
- 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress'.split(' '),
+ 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
- return function(scope, element, attr) {
- var fn = $parse(attr[directiveName]);
- element.bind(lowercase(name), function(event) {
- scope.$apply(function() {
- fn(scope, {$event:event});
- });
- });
+ return {
+ compile: function($element, attr) {
+ var fn = $parse(attr[directiveName]);
+ return function(scope, element, attr) {
+ element.on(lowercase(name), function(event) {
+ scope.$apply(function() {
+ fn(scope, {$event:event});
+ });
+ });
+ };
+ }
};
}];
}
@@ -13981,14 +18015,22 @@ forEach(
* @name ng.directive:ngDblclick
*
* @description
- * The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
+ * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
- * dblclick. (Event object is available as `$event`)
+ * a dblclick. (The Event object is available as `$event`)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ count: {{count}}
+
+
*/
@@ -14000,11 +18042,19 @@ forEach(
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ count: {{count}}
+
+
*/
@@ -14016,11 +18066,19 @@ forEach(
* Specify custom behavior on mouseup event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ count: {{count}}
+
+
*/
/**
@@ -14031,11 +18089,19 @@ forEach(
* Specify custom behavior on mouseover event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ count: {{count}}
+
+
*/
@@ -14047,11 +18113,19 @@ forEach(
* Specify custom behavior on mouseenter event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ count: {{count}}
+
+
*/
@@ -14063,11 +18137,19 @@ forEach(
* Specify custom behavior on mouseleave event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ count: {{count}}
+
+
*/
@@ -14079,11 +18161,19 @@ forEach(
* Specify custom behavior on mousemove event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ count: {{count}}
+
+
*/
@@ -14095,11 +18185,17 @@ forEach(
* Specify custom behavior on keydown event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
* keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ key down count: {{count}}
+
+
*/
@@ -14111,11 +18207,17 @@ forEach(
* Specify custom behavior on keyup event.
*
* @element ANY
+ * @priority 0
* @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
* keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ key up count: {{count}}
+
+
*/
@@ -14131,7 +18233,12 @@ forEach(
* keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
- * See {@link ng.directive:ngClick ngClick}
+
+
+
+ key press count: {{count}}
+
+
*/
@@ -14143,10 +18250,12 @@ forEach(
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
- * server and reloading the current page).
+ * server and reloading the current page) **but only if the form does not contain an `action`
+ * attribute**.
*
* @element form
- * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
+ * @priority 0
+ * @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`)
*
* @example
@@ -14170,27 +18279,235 @@ forEach(
list={{list}}
-
+
it('should check ng-submit', function() {
- expect(binding('list')).toBe('[]');
- element('.doc-example-live #submit').click();
- expect(binding('list')).toBe('["hello"]');
- expect(input('text').val()).toBe('');
+ expect(element(by.binding('list')).getText()).toBe('list=[]');
+ element(by.css('.doc-example-live #submit')).click();
+ expect(element(by.binding('list')).getText()).toContain('hello');
+ expect(element(by.input('text')).getAttribute('value')).toBe('');
});
it('should ignore empty strings', function() {
- expect(binding('list')).toBe('[]');
- element('.doc-example-live #submit').click();
- element('.doc-example-live #submit').click();
- expect(binding('list')).toBe('["hello"]');
- });
-
+ expect(element(by.binding('list')).getText()).toBe('list=[]');
+ element(by.css('.doc-example-live #submit')).click();
+ element(by.css('.doc-example-live #submit')).click();
+ expect(element(by.binding('list')).getText()).toContain('hello');
+ });
+
*/
-var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
- element.bind('submit', function() {
- scope.$apply(attrs.ngSubmit);
- });
-});
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngFocus
+ *
+ * @description
+ * Specify custom behavior on focus event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
+ * focus. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngBlur
+ *
+ * @description
+ * Specify custom behavior on blur event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
+ * blur. (Event object is available as `$event`)
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngCopy
+ *
+ * @description
+ * Specify custom behavior on copy event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
+ * copy. (Event object is available as `$event`)
+ *
+ * @example
+
+
+
+ copied: {{copied}}
+
+
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngCut
+ *
+ * @description
+ * Specify custom behavior on cut event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
+ * cut. (Event object is available as `$event`)
+ *
+ * @example
+
+
+
+ cut: {{cut}}
+
+
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngPaste
+ *
+ * @description
+ * Specify custom behavior on paste event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
+ * paste. (Event object is available as `$event`)
+ *
+ * @example
+
+
+
+ pasted: {{paste}}
+
+
+ */
+
+/**
+ * @ngdoc directive
+ * @name ng.directive:ngIf
+ * @restrict A
+ *
+ * @description
+ * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
+ * {expression}. If the expression assigned to `ngIf` evaluates to a false
+ * value then the element is removed from the DOM, otherwise a clone of the
+ * element is reinserted into the DOM.
+ *
+ * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
+ * element in the DOM rather than changing its visibility via the `display` css property. A common
+ * case when this difference is significant is when using css selectors that rely on an element's
+ * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
+ *
+ * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
+ * is created when the element is restored. The scope created within `ngIf` inherits from
+ * its parent scope using
+ * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}.
+ * An important implication of this is if `ngModel` is used within `ngIf` to bind to
+ * a javascript primitive defined in the parent scope. In this case any modifications made to the
+ * variable within the child scope will override (hide) the value in the parent scope.
+ *
+ * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
+ * is if an element's class attribute is directly modified after it's compiled, using something like
+ * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
+ * the added class will be lost because the original compiled state is used to regenerate the element.
+ *
+ * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
+ * and `leave` effects.
+ *
+ * @animations
+ * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
+ * leave - happens just before the ngIf contents are removed from the DOM
+ *
+ * @element ANY
+ * @scope
+ * @priority 600
+ * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
+ * the element is removed from the DOM tree. If it is truthy a copy of the compiled
+ * element is added to the DOM tree.
+ *
+ * @example
+
+
+ Click me:
+ Show when checked:
+
+ I'm removed when the checkbox is unchecked.
+
+
+
+ .animate-if {
+ background:white;
+ border:1px solid black;
+ padding:10px;
+ }
+
+ .animate-if.ng-enter, .animate-if.ng-leave {
+ -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ }
+
+ .animate-if.ng-enter,
+ .animate-if.ng-leave.ng-leave-active {
+ opacity:0;
+ }
+
+ .animate-if.ng-leave,
+ .animate-if.ng-enter.ng-enter-active {
+ opacity:1;
+ }
+
+
+ */
+var ngIfDirective = ['$animate', function($animate) {
+ return {
+ transclude: 'element',
+ priority: 600,
+ terminal: true,
+ restrict: 'A',
+ $$tlb: true,
+ link: function ($scope, $element, $attr, ctrl, $transclude) {
+ var block, childScope;
+ $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
+
+ if (toBoolean(value)) {
+ if (!childScope) {
+ childScope = $scope.$new();
+ $transclude(childScope, function (clone) {
+ clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
+ // Note: We only need the first/last node of the cloned nodes.
+ // However, we need to keep the reference to the jqlite wrapper as it might be changed later
+ // by a directive with templateUrl when it's template arrives.
+ block = {
+ clone: clone
+ };
+ $animate.enter(clone, $element.parent(), $element);
+ });
+ }
+ } else {
+
+ if (childScope) {
+ childScope.$destroy();
+ childScope = null;
+ }
+
+ if (block) {
+ $animate.leave(getBlockElements(block.clone));
+ block = null;
+ }
+ }
+ });
+ }
+ };
+}];
/**
* @ngdoc directive
@@ -14200,18 +18517,28 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
* @description
* Fetches, compiles and includes an external HTML fragment.
*
- * Keep in mind that Same Origin Policy applies to included resources
- * (e.g. ngInclude won't work for cross-domain requests on all browsers and for
- * file:// access on some browsers).
+ * By default, the template URL is restricted to the same domain and protocol as the
+ * application document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
+ * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
+ * you may either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist them} or
+ * {@link ng.$sce#methods_trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
+ * ng.$sce Strict Contextual Escaping}.
*
- * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
- * and **leave** effects.
+ * In addition, the browser's
+ * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
+ * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing
+ * (CORS)} policy may further restrict whether the template is successfully loaded.
+ * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
+ * access on some browsers.
*
* @animations
- * enter - happens just after the ngInclude contents change and a new DOM element is created and injected into the ngInclude container
- * leave - happens just after the ngInclude contents change and just before the former contents are removed from the DOM
+ * enter - animation is used to bring new content into the browser.
+ * leave - animation is used to animate existing content away.
+ *
+ * The enter and leave animation occur concurrently.
*
* @scope
+ * @priority 400
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
@@ -14225,7 +18552,7 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
-
+
+ Content of template2.html
- .example-leave-setup,
- .example-enter-setup {
+ .slide-animate-container {
+ position:relative;
+ background:white;
+ border:1px solid black;
+ height:40px;
+ overflow:hidden;
+ }
+
+ .slide-animate {
+ padding:10px;
+ }
+
+ .slide-animate.ng-enter, .slide-animate.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
- -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
- -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
- -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
@@ -14266,46 +18601,67 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
left:0;
right:0;
bottom:0;
- }
-
- .example-animate-container > * {
display:block;
padding:10px;
}
- .example-enter-setup {
+ .slide-animate.ng-enter {
top:-50px;
}
- .example-enter-setup.example-enter-start {
+ .slide-animate.ng-enter.ng-enter-active {
top:0;
}
- .example-leave-setup {
+ .slide-animate.ng-leave {
top:0;
}
- .example-leave-setup.example-leave-start {
+ .slide-animate.ng-leave.ng-leave-active {
top:50px;
}
-
+
+ var templateSelect = element(by.model('template'));
+ var includeElem = element(by.css('.doc-example-live [ng-include]'));
+
it('should load template1.html', function() {
- expect(element('.doc-example-live [ng-include]').text()).
- toMatch(/Content of template1.html/);
+ expect(includeElem.getText()).toMatch(/Content of template1.html/);
});
+
it('should load template2.html', function() {
- select('template').option('1');
- expect(element('.doc-example-live [ng-include]').text()).
- toMatch(/Content of template2.html/);
+ if (browser.params.browser == 'firefox') {
+ // Firefox can't handle using selects
+ // See https://github.com/angular/protractor/issues/480
+ return;
+ }
+ templateSelect.click();
+ templateSelect.element.all(by.css('option')).get(2).click();
+ expect(includeElem.getText()).toMatch(/Content of template2.html/);
});
+
it('should change to blank', function() {
- select('template').option('');
- expect(element('.doc-example-live [ng-include]').text()).toEqual('');
+ if (browser.params.browser == 'firefox') {
+ // Firefox can't handle using selects
+ return;
+ }
+ templateSelect.click();
+ templateSelect.element.all(by.css('option')).get(0).click();
+ expect(includeElem.isPresent()).toBe(false);
});
*/
+/**
+ * @ngdoc event
+ * @name ng.directive:ngInclude#$includeContentRequested
+ * @eventOf ng.directive:ngInclude
+ * @eventType emit on the scope ngInclude was declared in
+ * @description
+ * Emitted every time the ngInclude content is requested.
+ */
+
+
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
@@ -14314,56 +18670,72 @@ var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
* @description
* Emitted every time the ngInclude content is reloaded.
*/
-var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator',
- function($http, $templateCache, $anchorScroll, $compile, $animator) {
+var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
+ function($http, $templateCache, $anchorScroll, $animate, $sce) {
return {
restrict: 'ECA',
+ priority: 400,
terminal: true,
+ transclude: 'element',
+ controller: angular.noop,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
- return function(scope, element, attr) {
- var animate = $animator(scope, attr);
+ return function(scope, $element, $attr, ctrl, $transclude) {
var changeCounter = 0,
- childScope;
+ currentScope,
+ currentElement;
- var clearContent = function() {
- if (childScope) {
- childScope.$destroy();
- childScope = null;
+ var cleanupLastIncludeContent = function() {
+ if (currentScope) {
+ currentScope.$destroy();
+ currentScope = null;
+ }
+ if(currentElement) {
+ $animate.leave(currentElement);
+ currentElement = null;
}
- animate.leave(element.contents(), element);
};
- scope.$watch(srcExp, function ngIncludeWatchAction(src) {
+ scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
+ var afterAnimation = function() {
+ if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
+ $anchorScroll();
+ }
+ };
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
+ var newScope = scope.$new();
+ ctrl.template = response;
- if (childScope) childScope.$destroy();
- childScope = scope.$new();
- animate.leave(element.contents(), element);
+ // Note: This will also link all children of ng-include that were contained in the original
+ // html. If that content contains controllers, ... they could pollute/change the scope.
+ // However, using ng-include on an element with additional content does not make sense...
+ // Note: We can't remove them in the cloneAttchFn of $transclude as that
+ // function is called before linking the content, which would apply child
+ // directives to non existing elements.
+ var clone = $transclude(newScope, function(clone) {
+ cleanupLastIncludeContent();
+ $animate.enter(clone, null, $element, afterAnimation);
+ });
- var contents = jqLite('').html(response).contents();
+ currentScope = newScope;
+ currentElement = clone;
- animate.enter(contents, element);
- $compile(contents)(childScope);
-
- if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
- $anchorScroll();
- }
-
- childScope.$emit('$includeContentLoaded');
+ currentScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
- if (thisChangeId === changeCounter) clearContent();
+ if (thisChangeId === changeCounter) cleanupLastIncludeContent();
});
+ scope.$emit('$includeContentRequested');
} else {
- clearContent();
+ cleanupLastIncludeContent();
+ ctrl.template = null;
}
});
};
@@ -14371,13 +18743,48 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile'
};
}];
+// This directive is called during the $transclude call of the first `ngInclude` directive.
+// It will replace and compile the content of the element with the loaded template.
+// We need this directive so that the element content is already filled when
+// the link function of another directive on the same element as ngInclude
+// is called.
+var ngIncludeFillContentDirective = ['$compile',
+ function($compile) {
+ return {
+ restrict: 'ECA',
+ priority: -400,
+ require: 'ngInclude',
+ link: function(scope, $element, $attr, ctrl) {
+ $element.html(ctrl.template);
+ $compile($element.contents())(scope);
+ }
+ };
+ }];
+
/**
* @ngdoc directive
* @name ng.directive:ngInit
+ * @restrict AC
*
* @description
- * The `ngInit` directive specifies initialization tasks to be executed
- * before the template enters execution mode during bootstrap.
+ * The `ngInit` directive allows you to evaluate an expression in the
+ * current scope.
+ *
+ *
+ * The only appropriate use of `ngInit` is for aliasing special properties of
+ * {@link api/ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
+ * should use {@link guide/controller controllers} rather than `ngInit`
+ * to initialize values on a scope.
+ *
+ *
+ * **Note**: If you have assignment in `ngInit` along with {@link api/ng.$filter `$filter`}, make
+ * sure you have parenthesis for correct precedence:
+ *
-
- it('should check greeting', function() {
- expect(binding('greeting')).toBe('Hello');
- expect(binding('person')).toBe('World');
+
+ it('should alias index positions', function() {
+ var elements = element.all(by.css('.example-init'));
+ expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
+ expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
+ expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
+ expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
});
-
+
*/
var ngInitDirective = ngDirective({
+ priority: 450,
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
- }
+ };
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
+ * @restrict AC
* @priority 1000
*
* @description
- * Sometimes it is necessary to write code which looks like bindings but which should be left alone
- * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
+ * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
+ * DOM element. This is useful if the element contains what appears to be Angular directives and
+ * bindings but which should be ignored by Angular. This could be the case if you have a site that
+ * displays snippets of code, for instance.
*
* @element ANY
*
* @example
- * In this example there are two location where a simple binding (`{{}}`) is present, but the one
- * wrapped in `ngNonBindable` is left alone.
+ * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
+ * but the one wrapped in `ngNonBindable` is left alone.
*
* @example
@@ -14428,13 +18851,12 @@ var ngInitDirective = ngDirective({
Normal: {{1 + 2}}
Ignored: {{1 + 2}}
-
+
it('should check ng-non-bindable', function() {
- expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
- expect(using('.doc-example-live').element('div:last').text()).
- toMatch(/1 \+ 2/);
+ expect(element(by.binding('1 + 2')).getText()).toContain('3');
+ expect(element.all(by.css('.doc-example-live div')).last().getText()).toMatch(/1 \+ 2/);
});
-
+
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
@@ -14447,7 +18869,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
- * These rules are bundled with angular.js and the rules can be overridden
+ * These rules are bundled with angular.js, but can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
@@ -14460,8 +18882,8 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
*
* While a plural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
- * explicit number rule for "3" matches the number 3. You will see the use of plural categories
- * and explicit number rules throughout later parts of this documentation.
+ * explicit number rule for "3" matches the number 3. There are examples of plural categories
+ * and explicit number rules throughout the rest of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
@@ -14471,8 +18893,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
- * string to be displayed. The value of the attribute should be a JSON object so that Angular
- * can interpret it correctly.
+ * string to be displayed. The value of the attribute should be a JSON object.
*
* The following example shows how to configure ngPluralize:
*
@@ -14490,7 +18911,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
- * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
+ * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* `{{personCount}}`. The closed braces `{}` is a placeholder
* for {{numberExpression}}.
@@ -14563,49 +18984,53 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
-
+
it('should show correct pluralized string', function() {
- expect(element('.doc-example-live ng-pluralize:first').text()).
- toBe('1 person is viewing.');
- expect(element('.doc-example-live ng-pluralize:last').text()).
- toBe('Igor is viewing.');
+ var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
+ var withOffset = element.all(by.css('ng-pluralize')).get(1);
+ var countInput = element(by.model('personCount'));
- using('.doc-example-live').input('personCount').enter('0');
- expect(element('.doc-example-live ng-pluralize:first').text()).
- toBe('Nobody is viewing.');
- expect(element('.doc-example-live ng-pluralize:last').text()).
- toBe('Nobody is viewing.');
+ expect(withoutOffset.getText()).toEqual('1 person is viewing.');
+ expect(withOffset.getText()).toEqual('Igor is viewing.');
- using('.doc-example-live').input('personCount').enter('2');
- expect(element('.doc-example-live ng-pluralize:first').text()).
- toBe('2 people are viewing.');
- expect(element('.doc-example-live ng-pluralize:last').text()).
- toBe('Igor and Misko are viewing.');
+ countInput.clear();
+ countInput.sendKeys('0');
- using('.doc-example-live').input('personCount').enter('3');
- expect(element('.doc-example-live ng-pluralize:first').text()).
- toBe('3 people are viewing.');
- expect(element('.doc-example-live ng-pluralize:last').text()).
- toBe('Igor, Misko and one other person are viewing.');
+ expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
+ expect(withOffset.getText()).toEqual('Nobody is viewing.');
- using('.doc-example-live').input('personCount').enter('4');
- expect(element('.doc-example-live ng-pluralize:first').text()).
- toBe('4 people are viewing.');
- expect(element('.doc-example-live ng-pluralize:last').text()).
- toBe('Igor, Misko and 2 other people are viewing.');
+ countInput.clear();
+ countInput.sendKeys('2');
+
+ expect(withoutOffset.getText()).toEqual('2 people are viewing.');
+ expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
+
+ countInput.clear();
+ countInput.sendKeys('3');
+
+ expect(withoutOffset.getText()).toEqual('3 people are viewing.');
+ expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
+
+ countInput.clear();
+ countInput.sendKeys('4');
+
+ expect(withoutOffset.getText()).toEqual('4 people are viewing.');
+ expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
});
-
- it('should show data-binded names', function() {
- using('.doc-example-live').input('personCount').enter('4');
- expect(element('.doc-example-live ng-pluralize:last').text()).
- toBe('Igor, Misko and 2 other people are viewing.');
-
- using('.doc-example-live').input('person1').enter('Di');
- using('.doc-example-live').input('person2').enter('Vojta');
- expect(element('.doc-example-live ng-pluralize:last').text()).
- toBe('Di, Vojta and 2 other people are viewing.');
+ it('should show data-bound names', function() {
+ var withOffset = element.all(by.css('ng-pluralize')).get(1);
+ var personCount = element(by.model('personCount'));
+ var person1 = element(by.model('person1'));
+ var person2 = element(by.model('person2'));
+ personCount.clear();
+ personCount.sendKeys('4');
+ person1.clear();
+ person1.sendKeys('Di');
+ person2.clear();
+ person2.sendKeys('Vojta');
+ expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
});
-
+
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
@@ -14614,13 +19039,20 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
- whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
+ whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
offset = attr.offset || 0,
- whens = scope.$eval(whenExp),
+ whens = scope.$eval(whenExp) || {},
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
- endSymbol = $interpolate.endSymbol();
+ endSymbol = $interpolate.endSymbol(),
+ isWhen = /^when(Minus)?(.+)$/;
+ forEach(attr, function(expression, attributeName) {
+ if (isWhen.test(attributeName)) {
+ whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
+ element.attr(attr.$attr[attributeName]);
+ }
+ });
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
@@ -14633,7 +19065,7 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
- if (!whens[value]) value = $locale.pluralCat(value - offset);
+ if (!(value in whens)) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
@@ -14656,13 +19088,61 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
*
* Special properties are exposed on the local scope of each template instance, including:
*
- * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
- * * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
- * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
- * * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
+ * | Variable | Type | Details |
+ * |-----------|-----------------|-----------------------------------------------------------------------------|
+ * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
+ * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
+ * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
+ * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
+ * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
+ * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
*
- * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**,
- * **leave** and **move** effects.
+ * Creating aliases for these properties is possible with {@link api/ng.directive:ngInit `ngInit`}.
+ * This may be useful when, for instance, nesting ngRepeats.
+ *
+ * # Special repeat start and end points
+ * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
+ * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
+ * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
+ * up to and including the ending HTML tag where **ng-repeat-end** is placed.
+ *
+ * The example below makes use of this feature:
+ *
+ *
+ * Header {{ item }}
+ *
+ *
+ * Body {{ item }}
+ *
+ *
+ *
+ *
+ * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
+ *
+ *
+ * Header A
+ *
+ *
+ * Body A
+ *
+ *
+ *
+ * Header B
+ *
+ *
+ * Body B
+ *
+ *
+ *
+ *
+ * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
+ * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
*
* @animations
* enter - when a new item is added to the list or when an item is revealed after a filter
@@ -14678,7 +19158,7 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
- * For example: `track in cd.tracks`.
+ * For example: `album in artist.albums`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
@@ -14686,10 +19166,11 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
- * which can be used to associate the objects in the collection with the DOM elements. If no tractking function
+ * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
* is specified the ng-repeat associates elements by identity in the collection. It is an error to have
- * more then one tractking function to resolve to the same key. (This would mean that two distinct objects are
- * mapped to the same DOM element, which is not possible.)
+ * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
+ * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
+ * before specifying a tracking expression.
*
* For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements
* will be associated by item identity in the array.
@@ -14697,12 +19178,15 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM
- * element in the same way ian the DOM.
+ * element in the same way in the DOM.
*
- * For example: `item in items track by item.id` Is a typical pattern when the items come from the database. In this
+ * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
* case the object identity does not matter. Two objects are considered equivalent as long as their `id`
* property is same.
*
+ * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
+ * to items in conjunction with a tracking expression.
+ *
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
@@ -14722,113 +19206,120 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
]">
I have {{friends.length}} friends. They are:
-
-
+
+
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
- .example-repeat-enter-setup,
- .example-repeat-leave-setup,
- .example-repeat-move-setup {
+ .example-animate-container {
+ background:white;
+ border:1px solid black;
+ list-style:none;
+ margin:0;
+ padding:0 10px;
+ }
+
+ .animate-repeat {
+ line-height:40px;
+ list-style:none;
+ box-sizing:border-box;
+ }
+
+ .animate-repeat.ng-move,
+ .animate-repeat.ng-enter,
+ .animate-repeat.ng-leave {
-webkit-transition:all linear 0.5s;
- -moz-transition:all linear 0.5s;
- -ms-transition:all linear 0.5s;
- -o-transition:all linear 0.5s;
transition:all linear 0.5s;
}
- .example-repeat-enter-setup {
- line-height:0;
+ .animate-repeat.ng-leave.ng-leave-active,
+ .animate-repeat.ng-move,
+ .animate-repeat.ng-enter {
opacity:0;
- }
- .example-repeat-enter-setup.example-repeat-enter-start {
- line-height:20px;
- opacity:1;
+ max-height:0;
}
- .example-repeat-leave-setup {
+ .animate-repeat.ng-leave,
+ .animate-repeat.ng-move.ng-move-active,
+ .animate-repeat.ng-enter.ng-enter-active {
opacity:1;
- line-height:20px;
+ max-height:40px;
}
- .example-repeat-leave-setup.example-repeat-leave-start {
- opacity:0;
- line-height:0;
- }
-
- .example-repeat-move-setup { }
- .example-repeat-move-setup.example-repeat-move-start { }
-
- it('should render initial data set', function() {
- var r = using('.doc-example-live').repeater('ul li');
- expect(r.count()).toBe(10);
- expect(r.row(0)).toEqual(["1","John","25"]);
- expect(r.row(1)).toEqual(["2","Jessie","30"]);
- expect(r.row(9)).toEqual(["10","Samantha","60"]);
- expect(binding('friends.length')).toBe("10");
- });
+
+ var friends = element(by.css('.doc-example-live'))
+ .element.all(by.repeater('friend in friends'));
+
+ it('should render initial data set', function() {
+ expect(friends.count()).toBe(10);
+ expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
+ expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
+ expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
+ expect(element(by.binding('friends.length')).getText())
+ .toMatch("I have 10 friends. They are:");
+ });
it('should update repeater when filter predicate changes', function() {
- var r = using('.doc-example-live').repeater('ul li');
- expect(r.count()).toBe(10);
+ expect(friends.count()).toBe(10);
- input('q').enter('ma');
+ element(by.css('.doc-example-live')).element(by.model('q')).sendKeys('ma');
- expect(r.count()).toBe(2);
- expect(r.row(0)).toEqual(["1","Mary","28"]);
- expect(r.row(1)).toEqual(["2","Samantha","60"]);
+ expect(friends.count()).toBe(2);
+ expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
+ expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
});
*/
-var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
+var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
+ var ngRepeatMinErr = minErr('ngRepeat');
return {
transclude: 'element',
priority: 1000,
terminal: true,
- compile: function(element, attr, linker) {
- return function($scope, $element, $attr){
- var animate = $animator($scope, $attr);
+ $$tlb: true,
+ link: function($scope, $element, $attr, ctrl, $transclude){
var expression = $attr.ngRepeat;
- var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
- trackByExp, hashExpFn, trackByIdFn, lhs, rhs, valueIdentifier, keyIdentifier,
+ var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
+ trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
+ lhs, rhs, valueIdentifier, keyIdentifier,
hashFnLocals = {$id: hashKey};
if (!match) {
- throw Error("Expected ngRepeat in form of '_item_ in _collection_[ track by _id_]' but got '" +
- expression + "'.");
+ throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
+ expression);
}
lhs = match[1];
rhs = match[2];
- trackByExp = match[4];
+ trackByExp = match[3];
if (trackByExp) {
- hashExpFn = $parse(trackByExp);
- trackByIdFn = function(key, value, index) {
+ trackByExpGetter = $parse(trackByExp);
+ trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
- return hashExpFn($scope, hashFnLocals);
+ return trackByExpGetter($scope, hashFnLocals);
};
} else {
- trackByIdFn = function(key, value) {
+ trackByIdArrayFn = function(key, value) {
return hashKey(value);
- }
+ };
+ trackByIdObjFn = function(key) {
+ return key;
+ };
}
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
- throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
- lhs + "'.");
+ throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
+ lhs);
}
valueIdentifier = match[3] || match[1];
keyIdentifier = match[2];
@@ -14843,8 +19334,8 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
//watch props
$scope.$watchCollection(rhs, function ngRepeatAction(collection){
var index, length,
- cursor = $element, // current position of the node
- nextCursor,
+ previousNode = $element[0], // current position of the node
+ nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = {},
@@ -14852,14 +19343,18 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
childScope,
key, value, // key/value of iteration
trackById,
+ trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
- nextBlockOrder = [];
+ nextBlockOrder = [],
+ elementsToRemove;
- if (isArray(collection)) {
+ if (isArrayLike(collection)) {
collectionKeys = collection;
+ trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
+ trackByIdFn = trackByIdExpFn || trackByIdObjFn;
// if object, extract keys, sort them and use to determine order of iteration over obj props
collectionKeys = [];
for (key in collection) {
@@ -14878,29 +19373,35 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
trackById = trackByIdFn(key, value, index);
- if((block = lastBlockMap[trackById])) {
+ assertNotHasOwnProperty(trackById, '`track by` id');
+ if(lastBlockMap.hasOwnProperty(trackById)) {
+ block = lastBlockMap[trackById];
delete lastBlockMap[trackById];
nextBlockMap[trackById] = block;
nextBlockOrder[index] = block;
} else if (nextBlockMap.hasOwnProperty(trackById)) {
// restore lastBlockMap
forEach(nextBlockOrder, function(block) {
- if (block && block.element) lastBlockMap[block.id] = block;
+ if (block && block.scope) lastBlockMap[block.id] = block;
});
// This is a duplicate and we need to throw an error
- throw new Error('Duplicates in a repeater are not allowed. Repeater: ' + expression);
+ throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
+ expression, trackById);
} else {
// new never before seen block
nextBlockOrder[index] = { id: trackById };
+ nextBlockMap[trackById] = false;
}
}
// remove existing items
for (key in lastBlockMap) {
+ // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
if (lastBlockMap.hasOwnProperty(key)) {
block = lastBlockMap[key];
- animate.leave(block.element);
- block.element[0][NG_REMOVED] = true;
+ elementsToRemove = getBlockElements(block.clone);
+ $animate.leave(elementsToRemove);
+ forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
block.scope.$destroy();
}
}
@@ -14910,25 +19411,23 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
+ if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
- if (block.element) {
+ if (block.scope) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = block.scope;
- nextCursor = cursor[0];
+ nextNode = previousNode;
do {
- nextCursor = nextCursor.nextSibling;
- } while(nextCursor && nextCursor[NG_REMOVED]);
+ nextNode = nextNode.nextSibling;
+ } while(nextNode && nextNode[NG_REMOVED]);
- if (block.element[0] == nextCursor) {
- // do nothing
- cursor = block.element;
- } else {
+ if (getBlockStart(block) != nextNode) {
// existing item which got moved
- animate.move(block.element, null, cursor);
- cursor = block.element;
+ $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
}
+ previousNode = getBlockEnd(block);
} else {
// new item which we don't know about
childScope = $scope.$new();
@@ -14940,22 +19439,36 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
childScope.$first = (index === 0);
childScope.$last = (index === (arrayLength - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
+ // jshint bitwise: false
+ childScope.$odd = !(childScope.$even = (index&1) === 0);
+ // jshint bitwise: true
- if (!block.element) {
- linker(childScope, function(clone) {
- animate.enter(clone, null, cursor);
- cursor = clone;
+ if (!block.scope) {
+ $transclude(childScope, function(clone) {
+ clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
+ $animate.enter(clone, null, jqLite(previousNode));
+ previousNode = clone;
block.scope = childScope;
- block.element = clone;
+ // Note: We only need the first/last node of the cloned nodes.
+ // However, we need to keep the reference to the jqlite wrapper as it might be changed later
+ // by a directive with templateUrl when it's template arrives.
+ block.clone = clone;
nextBlockMap[block.id] = block;
});
}
}
lastBlockMap = nextBlockMap;
});
- };
}
};
+
+ function getBlockStart(block) {
+ return block.clone[0];
+ }
+
+ function getBlockEnd(block) {
+ return block.clone[block.clone.length - 1];
+ }
}];
/**
@@ -14963,19 +19476,83 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
* @name ng.directive:ngShow
*
* @description
- * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
- * conditionally based on **"truthy"** values evaluated within an {expression}. In other
- * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible**
- * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none).
- * With ngHide this is the reverse whereas true values cause the element itself to become
- * hidden.
+ * The `ngShow` directive shows or hides the given HTML element based on the expression
+ * provided to the ngShow attribute. The element is shown or hidden by removing or adding
+ * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
+ * in AngularJS and sets the display style to none (using an !important flag).
+ * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
- * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show**
- * and **hide** effects.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
+ * on the element causing it to become hidden. When true, the ng-hide CSS class is removed
+ * from the element causing the element not to appear hidden.
+ *
+ * ## Why is !important used?
+ *
+ * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
+ * can be easily overridden by heavier selectors. For example, something as simple
+ * as changing the display style on a HTML list item would make hidden elements appear visible.
+ * This also becomes a bigger issue when dealing with CSS frameworks.
+ *
+ * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
+ * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
+ * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
+ *
+ * ### Overriding .ng-hide
+ *
+ * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
+ * restating the styles for the .ng-hide class in CSS:
+ *
+ * .ng-hide {
+ * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
+ * display:block!important;
+ *
+ * //this is just another form of hiding an element
+ * position:absolute;
+ * top:-9999px;
+ * left:-9999px;
+ * }
+ *
+ *
+ * Just remember to include the important flag so the CSS override will function.
+ *
+ *
+ * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):
+ * "f" / "0" / "false" / "no" / "n" / "[]"
+ *
+ *
+ * ## A note about animations with ngShow
+ *
+ * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
+ * is true and false. This system works like the animation system present with ngClass except that
+ * you must also include the !important flag to override the display property
+ * so that you can perform an animation when the element is hidden during the time of the animation.
+ *
+ *
+ * //
+ * //a working example can be found at the bottom of this page
+ * //
+ * .my-element.ng-hide-add, .my-element.ng-hide-remove {
+ * transition:0.5s linear all;
+ * display:block!important;
+ * }
+ *
+ * .my-element.ng-hide-add { ... }
+ * .my-element.ng-hide-add.ng-hide-add-active { ... }
+ * .my-element.ng-hide-remove { ... }
+ * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
+ *
*
* @animations
- * show - happens after the ngShow expression evaluates to a truthy value and the contents are set to visible
- * hide - happens before the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
+ * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
+ * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
@@ -14987,36 +19564,21 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
Click me:
Show:
-
+
I show up when your checkbox is checked.
-
+
Hide:
-
+
I hide when your checkbox is checked.
-
+
- .example-show-setup, .example-hide-setup {
+ .animate-show {
-webkit-transition:all linear 0.5s;
- -moz-transition:all linear 0.5s;
- -ms-transition:all linear 0.5s;
- -o-transition:all linear 0.5s;
transition:all linear 0.5s;
- }
-
- .example-show-setup {
- line-height:0;
- opacity:0;
- padding:0 10px;
- }
- .example-show-start.example-show-start {
line-height:20px;
opacity:1;
padding:10px;
@@ -15024,14 +19586,12 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
background:white;
}
- .example-hide-setup {
- line-height:20px;
- opacity:1;
- padding:10px;
- border:1px solid black;
- background:white;
+ .animate-show.ng-hide-add,
+ .animate-show.ng-hide-remove {
+ display:block!important;
}
- .example-hide-start.example-hide-start {
+
+ .animate-show.ng-hide {
line-height:0;
opacity:0;
padding:0 10px;
@@ -15043,25 +19603,26 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
background:white;
}
-
- it('should check ng-show / ng-hide', function() {
- expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
- expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
+
+ var thumbsUp = element(by.css('.doc-example-live span.icon-thumbs-up'));
+ var thumbsDown = element(by.css('.doc-example-live span.icon-thumbs-down'));
- input('checked').check();
+ it('should check ng-show / ng-hide', function() {
+ expect(thumbsUp.isDisplayed()).toBeFalsy();
+ expect(thumbsDown.isDisplayed()).toBeTruthy();
- expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
- expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
- });
+ element(by.model('checked')).click();
+
+ expect(thumbsUp.isDisplayed()).toBeTruthy();
+ expect(thumbsDown.isDisplayed()).toBeFalsy();
+ });
*/
-//TODO(misko): refactor to remove element from the DOM
-var ngShowDirective = ['$animator', function($animator) {
+var ngShowDirective = ['$animate', function($animate) {
return function(scope, element, attr) {
- var animate = $animator(scope, attr);
scope.$watch(attr.ngShow, function ngShowWatchAction(value){
- animate[toBoolean(value) ? 'show' : 'hide'](element);
+ $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
});
};
}];
@@ -15072,19 +19633,83 @@ var ngShowDirective = ['$animator', function($animator) {
* @name ng.directive:ngHide
*
* @description
- * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
- * conditionally based on **"truthy"** values evaluated within an {expression}. In other
- * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible**
- * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none).
- * With ngHide this is the reverse whereas true values cause the element itself to become
- * hidden.
+ * The `ngHide` directive shows or hides the given HTML element based on the expression
+ * provided to the ngHide attribute. The element is shown or hidden by removing or adding
+ * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
+ * in AngularJS and sets the display style to none (using an !important flag).
+ * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
- * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show**
- * and **hide** effects.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
+ * on the element causing it to become hidden. When false, the ng-hide CSS class is removed
+ * from the element causing the element not to appear hidden.
+ *
+ * ## Why is !important used?
+ *
+ * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
+ * can be easily overridden by heavier selectors. For example, something as simple
+ * as changing the display style on a HTML list item would make hidden elements appear visible.
+ * This also becomes a bigger issue when dealing with CSS frameworks.
+ *
+ * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
+ * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
+ * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
+ *
+ * ### Overriding .ng-hide
+ *
+ * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
+ * restating the styles for the .ng-hide class in CSS:
+ *
+ * .ng-hide {
+ * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
+ * display:block!important;
+ *
+ * //this is just another form of hiding an element
+ * position:absolute;
+ * top:-9999px;
+ * left:-9999px;
+ * }
+ *
+ *
+ * Just remember to include the important flag so the CSS override will function.
+ *
+ *
+ * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):
+ * "f" / "0" / "false" / "no" / "n" / "[]"
+ *
+ *
+ * ## A note about animations with ngHide
+ *
+ * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
+ * is true and false. This system works like the animation system present with ngClass, except that
+ * you must also include the !important flag to override the display property so
+ * that you can perform an animation when the element is hidden during the time of the animation.
+ *
+ *
+ * //
+ * //a working example can be found at the bottom of this page
+ * //
+ * .my-element.ng-hide-add, .my-element.ng-hide-remove {
+ * transition:0.5s linear all;
+ * display:block!important;
+ * }
+ *
+ * .my-element.ng-hide-add { ... }
+ * .my-element.ng-hide-add.ng-hide-add-active { ... }
+ * .my-element.ng-hide-remove { ... }
+ * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
+ *
*
* @animations
- * show - happens after the ngHide expression evaluates to a non truthy value and the contents are set to visible
- * hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
+ * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
+ * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
@@ -15096,36 +19721,21 @@ var ngShowDirective = ['$animator', function($animator) {
Click me:
Show:
-
+
I show up when your checkbox is checked.
-
+
Hide:
-
+
I hide when your checkbox is checked.
-
+
- .example-show-setup, .example-hide-setup {
+ .animate-hide {
-webkit-transition:all linear 0.5s;
- -moz-transition:all linear 0.5s;
- -ms-transition:all linear 0.5s;
- -o-transition:all linear 0.5s;
transition:all linear 0.5s;
- }
-
- .example-show-setup {
- line-height:0;
- opacity:0;
- padding:0 10px;
- }
- .example-show-start.example-show-start {
line-height:20px;
opacity:1;
padding:10px;
@@ -15133,14 +19743,12 @@ var ngShowDirective = ['$animator', function($animator) {
background:white;
}
- .example-hide-setup {
- line-height:20px;
- opacity:1;
- padding:10px;
- border:1px solid black;
- background:white;
+ .animate-hide.ng-hide-add,
+ .animate-hide.ng-hide-remove {
+ display:block!important;
}
- .example-hide-start.example-hide-start {
+
+ .animate-hide.ng-hide {
line-height:0;
opacity:0;
padding:0 10px;
@@ -15152,25 +19760,26 @@ var ngShowDirective = ['$animator', function($animator) {
background:white;
}
-
- it('should check ng-show / ng-hide', function() {
- expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1);
- expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1);
+
+ var thumbsUp = element(by.css('.doc-example-live span.icon-thumbs-up'));
+ var thumbsDown = element(by.css('.doc-example-live span.icon-thumbs-down'));
- input('checked').check();
+ it('should check ng-show / ng-hide', function() {
+ expect(thumbsUp.isDisplayed()).toBeFalsy();
+ expect(thumbsDown.isDisplayed()).toBeTruthy();
- expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1);
- expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1);
- });
+ element(by.model('checked')).click();
+
+ expect(thumbsUp.isDisplayed()).toBeTruthy();
+ expect(thumbsDown.isDisplayed()).toBeFalsy();
+ });
*/
-//TODO(misko): refactor to remove element from the DOM
-var ngHideDirective = ['$animator', function($animator) {
+var ngHideDirective = ['$animate', function($animate) {
return function(scope, element, attr) {
- var animate = $animator(scope, attr);
scope.$watch(attr.ngHide, function ngHideWatchAction(value){
- animate[toBoolean(value) ? 'hide' : 'show'](element);
+ $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
});
};
}];
@@ -15178,6 +19787,7 @@ var ngHideDirective = ['$animator', function($animator) {
/**
* @ngdoc directive
* @name ng.directive:ngStyle
+ * @restrict AC
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
@@ -15201,13 +19811,15 @@ var ngHideDirective = ['$animator', function($animator) {
color: black;
}
-
+
+ var colorSpan = element(by.css('.doc-example-live span'));
+
it('should check ng-style', function() {
- expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
- element('.doc-example-live :button[value=set]').click();
- expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
- element('.doc-example-live :button[value=clear]').click();
- expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
+ expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
+ element(by.css('.doc-example-live input[value=set]')).click();
+ expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
+ element(by.css('.doc-example-live input[value=clear]')).click();
+ expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
});
@@ -15227,24 +19839,28 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) {
* @restrict EA
*
* @description
- * The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression.
- * Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location
+ * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
+ * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
* as specified in the template.
*
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
- * from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element
+ * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
* matches the value obtained from the evaluated expression. In other words, you define a container element
- * (where you place the directive), place an expression on the **on="..." attribute**
- * (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place
+ * (where you place the directive), place an expression on the **`on="..."` attribute**
+ * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
* a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
* attribute is displayed.
*
- * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
- * and **leave** effects.
- *
+ *
+ * Be aware that the attribute values to match against cannot be expressions. They are interpreted
+ * as literal string values to match against.
+ * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
+ * value of the expression `$scope.someVal`.
+ *
+
* @animations
- * enter - happens after the ngSwtich contents change and the matched child element is placed inside the container
+ * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
* leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
*
* @usage
@@ -15254,7 +19870,9 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) {
* ...
*
*
+ *
* @scope
+ * @priority 800
* @param {*} ngSwitch|on expression to match against ng-switch-when.
* @paramDescription
* On child elements add:
@@ -15275,13 +19893,11 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) {
selection={{selection}}
-
' +
'' +
@@ -15445,254 +20060,59 @@ var ngSwitchDefaultDirective = ngDirective({
{{text}}
-
+
it('should have transcluded', function() {
- input('title').enter('TITLE');
- input('text').enter('TEXT');
- expect(binding('title')).toEqual('TITLE');
- expect(binding('text')).toEqual('TEXT');
+ var titleElement = element(by.model('title'));
+ titleElement.clear();
+ titleElement.sendKeys('TITLE');
+ var textElement = element(by.model('text'));
+ textElement.clear();
+ textElement.sendKeys('TEXT');
+ expect(element(by.binding('title')).getText()).toEqual('TITLE');
+ expect(element(by.binding('text')).getText()).toEqual('TEXT');
});
-
+
*
*/
var ngTranscludeDirective = ngDirective({
- controller: ['$transclude', '$element', function($transclude, $element) {
- $transclude(function(clone) {
+ controller: ['$element', '$transclude', function($element, $transclude) {
+ if (!$transclude) {
+ throw minErr('ngTransclude')('orphan',
+ 'Illegal use of ngTransclude directive in the template! ' +
+ 'No parent directive that requires a transclusion found. ' +
+ 'Element: {0}',
+ startingTag($element));
+ }
+
+ // remember the transclusion fn but call it during linking so that we don't process transclusion before directives on
+ // the parent element even when the transclusion replaces the current element. (we can't use priority here because
+ // that applies only to compile fns and not controllers
+ this.$transclude = $transclude;
+ }],
+
+ link: function($scope, $element, $attrs, controller) {
+ controller.$transclude(function(clone) {
+ $element.empty();
$element.append(clone);
});
- }]
+ }
});
-/**
- * @ngdoc directive
- * @name ng.directive:ngView
- * @restrict ECA
- *
- * @description
- * # Overview
- * `ngView` is a directive that complements the {@link ng.$route $route} service by
- * including the rendered template of the current route into the main layout (`index.html`) file.
- * Every time the current route changes, the included view changes with it according to the
- * configuration of the `$route` service.
- *
- * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
- * and **leave** effects.
- *
- * @animations
- * enter - happens just after the ngView contents are changed (when the new view DOM element is inserted into the DOM)
- * leave - happens just after the current ngView contents change and just before the former contents are removed from the DOM
- *
- * @scope
- * @example
-
-
-