Rather than giving them a budget of $X to accomplish goal Y, specific rocket designs and decisions are written into the budget to try to ensure facilities and contractors in various states are given a slice of the pie.
SpaceX's success has come with direct partnership with NASA, within specific projects where those inside NASA fought to run the development as an open bid for commercial services, rather than as NASA-engineered projects with work doled out to cost-plus defense industry contractors. SpaceX is not the only beneficiary of these projects, the goal is to try to cultivate multiple successful service providers that can sustain their own businesses.
There has been plenty of opposition to these commercial bid projects within congress, but the success and efficiency of these projects so far have made them hard to argue against.
NASA also wrote SpaceX checks for the development of Falcon 9, the Dragon cargo capsule for space station resupply missions, the Dragon crew capsule for space station crew missions, and various other probe and satellite launches along the way.
I think these were good contracts that benefited both organizations massively, let SpaceX survive, and let NASA contract for services without paying the entire development cost since that was shared with SpaceX's own investment and other customers.
But it's definitely not a situation that can be boiled down to SpaceX vs NASA, it's been SpaceX and NASA together since the Falcon 9 development program began.
SpaceX can take as much (bussiness) risk as Musk deems acceptable
Some of them, though, really know what they're doing and are just better at doing stuff.
SpaceX want (and need) to deliver the best viable product to market as soon as possible, everyone involved is focused on this singular vision.
NASA will have its funding cut or expanded on a 4-8 year basis. Politicians, agencies, states and other companies will lobby to get investment in their preferred areas. Even scientists/departments/entire universities will lobby to get their personal pet projects on to a mission to further their own agendas.
Frankly im unsure how a public space program can even operate most the time.
Also NASA is a former of it's self, funding wise.
The difference is that a faction within NASA has been fighting to run these and other projects as open-bid commercial service contracts, where NASA can provide detailed requirements but not dictate specifically where and how the vehicles are built, and this has encouraged diversity and competition in these markets.
Traditional NASA development projects (like the SLS rocket) are micromanaged by congress in the budget, where congress dictates specifics of rocket design to ensure specific contractors in specific states receive a slice of the pie in defense-industry style cost-plus contracts.