簡體   English   中英

Angular $ scope.variable undefined

[英]Angular $scope.variable undefined

我遇到的問題是,當使用角度函數ng-repeat時,我的$ scope.todo列表總是返回undefined。 如果我定義$ scope.todo它可以很好地工作,但是當我使用下面的解決方案獲取結果並將其添加到變量時,我得到一個未定義的,它似乎有機會去檢索正確的值

我現在添加了一些更好的代碼來解釋我的問題。 在查看下面的一些jsfiddles並嘗試這些解決方案后,我開始認為它與我的回調有關。

function TodoCtrl($scope) {

   $scope.todos = [];

   buildInitialList(function (result){
       console.log(result); //Logs defined after the undefined below
       $scope.todos = result;
   });

   console.log($scope.todos); //Logs undefined before the defined log above
}

function buildInitialList(callback){
    //Simulates call to db
    setTimeout(function (){
    callback([{text: 'item 1', done: false},
        {text: 'item 2', done: false}]);
},2000);
}

function fetch(url, callback) {
    $.getJSON(url, function (data, status) {
        callback(data);
    });
}

不應該這樣:

$scope.testList = buildInitialList(function (result){
     return result;
   }

是這樣的:

$scope.testList = buildInitialList( function (result){return result;} );

而且buildInitialList函數沒有返回任何值。 根據您的示例代碼,它可能是這樣的:

function buildInitialList(callback){
   var result = doWorkAndGetResult();
   callback(result);
  //missing return value...
   return result; /*maybe?*/
}

這是一個完全有效的jsfiddle演示:

http://jsfiddle.net/f9ee4/1/

您實際上從未將結果分配給范圍變量。 正在調用您的回調函數,但回調的返回值不是分配給您的scope屬性的值。

通過使用回調,我假設你在該全局函數中有某種異步調用。 如果你沒有異步調用,那么你應該只返回buildInitialList中的值,而不使用回調。

這是一個有效的小提琴: http//jsfiddle.net/973nW/

function MyCtrl($scope) {
    buildInitialList(function (result){
        $scope.name = result;
    });  
}

附注:使用全局函數不是一個好主意,您可能需要考慮將您的函數放入服務中。

把我的頭發拉出來並且認為我的javascript出了問題之后,事實證明問題實際上是在我在HTML中使用的ng-repeat中

這就是我的html看起來像

<ul class="unstyled">
        <li ng-repeat="todo in todos">
            <input type="checkbox" ng-model="todo.done">
            <span class="done-{{todo.done}}">{{todo.text}}</span>
        </li>
</ul>

當我從一開始就定義了ToDo的列表時,這很好用,但是當我不得不去DB並檢索該列表時,結果似乎從未應用到原始$ scope.todos

我必須使用$ scope。$ apply函數來確保從數據庫中檢索到我的值后,它們實際應用於$ scope

buildInitialList(function (result){
    $scope.$apply(function (){
        console.log(result);
        $scope.todos = result;
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM