Angular.js动态设置提交按钮值失效,求排查解决方法
Hey there, let's get your dynamic submit button working properly! I spotted two key issues in your current code that are keeping it from behaving as expected.
First, using interpolation ({{}}) directly in the value attribute of your submit input doesn't play well with Angular's dynamic updates. Angular has a dedicated directive called ng-value that's built specifically for binding dynamic values to input elements, which handles changes much more reliably.
Second, your HTML is missing the ng-app directive—this is required to bootstrap your AngularJS application. Without it, Angular won't recognize any of your scope bindings or directives.
Here's the corrected code that should fix both problems:
HTML:
<body ng-app="myApp" ng-controller="MainCtrl"> <input type="submit" ng-value="!model ? 'reset' : model" /> </body>
JavaScript:
var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.model = "Create new order"; });
Let me break down the changes:
- Added
ng-app="myApp"to the<body>tag (you could also place it on the<html>tag) to tell Angular which module to use for your application. - Swapped
value="{{ !model ? 'reset' : model}}"forng-value="!model ? 'reset' : model". Theng-valuedirective automatically watches the expression and updates the button's text whenever$scope.modelchanges.
Now, when $scope.model has a value (like "Create new order"), the button will display that text. If $scope.model is undefined, null, or an empty string, the button will switch to showing "reset" right away. To test this, just set $scope.model = undefined; in your controller and watch the button update.
内容的提问来源于stack exchange,提问作者user5443928

