Angularjs 在$watch block中设置角度变量

Angularjs 在$watch block中设置角度变量,angularjs,watch,Angularjs,Watch,我有以下资料: var s= ''; $scope.$watch('foos', function(newValue, oldValue) { for(var i=0; i< newValue.length; i++){ var name= newValue[i].barName; //console.log(name); s += na

我有以下资料:

        var s= '';
        $scope.$watch('foos', function(newValue, oldValue) {

            for(var i=0; i< newValue.length; i++){
                var name= newValue[i].barName;
                //console.log(name);
                s += name;
                s += "--";
            }
        });
        console.log(s);
“foos”来自一个餐馆的电话,所以这是一个承诺,所以我不得不用一块美元的手表来包装它。 我想设置's',然后在$watch块之外使用's',就像我有console.log的地方一样。 现在的情况是,“s”总是空的,如何使它在$watch块中设置后使用?

只有在它准备好后,才能使用它,下面是一种方法:

 link: function($scope, $element, $attrs) {
    var s= '';
    $scope.$watch('foos', function(newValue, oldValue) {

        for(var i=0; i< newValue.length; i++){
            var name= newValue[i].barName;
            //console.log(name);
            s += name;
            s += "--";
        }
        if(s.length > 0)
            doStuffWithS($scope, $element, $compile, s);
    });


}

    function doStuffWithS($scope, $element, $compile, s) {
        // it goes here...

        $element[0].outerHTML("<div class='me'>" + s + "</div>";
        $compile($element.contents())($scope);

     }

我得到的错误是:TypeError:cannotread属性'replaceChild'为null

thx。要获得帮助,您能否为我回答这个问题……我在一个指令中有一个$watch,该指令的任务是替换元素。我编辑了我的问题,并加入了你的答案,但有些地方不对劲,你能提出任何建议吗?我在Dostuffiss中添加了ifs.length>0作为条件,并且似乎一切都正常……你认为这样做有什么问题吗?没有问题。检查newValue的长度似乎更直观,但s也可以。很高兴你让它工作了。