Defined such a module and used angular’s native ngRoute
var app = angular.module('NewsPub', ['ngRoute']);
//配置路由,controller为下面定义的AddController
app.config['$routeProvider', function($routeProvider) {
$routeProvider.when('/add', {templateUrl: add.html,controller: 'AddController'});
}
app.controller('AddController',function($scope){
$scope.title = '';
var a = {prop: $scope.title};
$scope.add = function(){
console.dir(a);
}
});
In the ng-template with ID add.html
, we use ng-model to bind the value of title
in $scope
, and set the button binding Define add() event
<input type="text" ng-model="title" value="标题">
<span>{{title}}</span>
<button ng-click="add()">Btn</button>
Now comes the problem. As shown in the figure below, if you change the value in the input
box, the value in <span>
will change accordingly. This shows that there is a two-way binding of the data. is fixed, that is, $scope.title
will change as the value in the input
box changes.
However, no matter how you change the value in the input
box and click the button
to trigger the add() event, the console outputs the a
object's prop
The property is always the initial value of $scope.title''
(will not change when the value of title changes)
Please ask the master to help me, I am a novice, I have been working on it for a long time and I still can’t figure it out, I am endlessly grateful!
The input on your page is bound to $scope.title, not your a.prop. What you entered and changed in the input is $scope.title. Angular changed it for you, but no one has access to your a.prop. Then assign a value to it, so it will always be the value you assigned at the beginning, which is "".
This is a variable reference problem
`$scope.title = '';
Created two object property references to
''
的引用,你改变了$scope.title
的值,就是断掉了$scope.title
的引用,但是a.prop
依然保持对''
It is recommended to read the article Understanding the Scope of AngularJS.