Local bacterial infection is a challenging task and still remains a serious threat to human health in clinics. Systemic administration of antibiotics has only short-term antibacterial activity and usually causes adverse effects and bacterial resistance. A bioadhesive hydrogel with broad-spectrum and on-demand antibiotic activity is highly desirable. Here, we designed a pH-responsive nanocomposite hydrogel via a Schiff base linkage between oxidized polysaccharides and cationic dendrimers encapsulated with silver nanoparticles. The antibacterial components, both the cationic dendrimers and silver species, could be released in response to the acidity generated by growing bacteria. The released cationic polymer and silver exhibited a synergistic effect in antibacterial activity, and thus, the nanocomposite hydrogel showed potent antibacterial activity against both Gram-negative ( Escherichia coli and Pseudomonas aeruginosa) and Gram-positive bacteria ( Staphylococcus epidermidis and Staphylococcus aureus). The gel showed superior in vivo antibacterial efficacy against S. aureus infection compared with a commercial silver hydrogel at the same silver concentration. In addition, no obvious hemolytic toxicity, cytotoxicity, and tissue and biochemical toxicity were observed for the antibacterial hydrogel after incubation with cells or implantation. This study provides a facile and promising strategy to develop smart hydrogels to treat local bacterial infections.