javascript - Help Angular 1 Why assigning values ​​to object properties in $scope does not work (scope problem), thank you endlessly!
巴扎黑
巴扎黑 2017-05-16 13:20:13
0
3
579

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 propThe 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!

巴扎黑
巴扎黑

reply all(3)
迷茫

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 = '';

var a = {prop: $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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!