suchen

Heim  >  Fragen und Antworten  >  Hauptteil

javascript - Hilfe Angular 1 Warum das Zuweisen von Werten zu Objekteigenschaften in $scope nicht funktioniert (Bereichsproblem), vielen Dank!

Definieren Sie ein solches Modul und verwenden Sie Angulars natives 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);
    }            
});

Am Wert mit der ID add.html的ng-template使用了ng-model绑定了$scopetitle und die Schaltfläche zum Binden des add()-Ereignisses festlegen

<input type="text" ng-model="title" value="标题">
<span>{{title}}</span>
<button ng-click="add()">Btn</button>

Jetzt tritt das Problem auf, wie in der Abbildung unten gezeigt. Ändern Sie den Wert im Feld input框内的值,<span>内的值会跟着改变,这说明数据有存在双向绑定,即$scope.title会随着input.

Jedoch, egal wie es sich ändertinput框内的值,点击button内触发add()事件时,控制台输出的a对象的prop属性永远是$scope.title的初始值'' ( ändert sich nicht, wenn sich der Wert des Titels ändert)

Bitte bitte den Meister, mir zu helfen, ich bin ein Neuling und kann es nach langer Zeit nicht mehr herausfinden, ich bin unendlich dankbar!

巴扎黑巴扎黑2864 Tage vor638

Antworte allen(3)Ich werde antworten

  • 迷茫

    迷茫2017-05-16 13:22:13

    你页面的input绑定的是$scope.title,而不是你的a.prop,你在input里面输入改变的是$scope.title,是angular帮你改变的,但是你的a.prop没人再赋值给它啊,所以一直都是你开始赋的值,就是""。

    Antwort
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:22:13

    这是变量引用问题
    `$scope.title = '';

    var a = {prop: $scope.title};`

    创建了两个对象属性对''的引用,你改变了$scope.title的值,就是断掉了$scope.title的引用,但是a.prop依然保持对''的引用

    Antwort
    0
  • 迷茫

    迷茫2017-05-16 13:22:13

    建议看一下 理解AngularJS的作用域Scope 这篇文章。

    Antwort
    0
  • StornierenAntwort