2015-09-25 35 views
1

我正在圍繞帶有隔離作用域的角度指令進行遊戲。 我剛剛面對一個有趣的情況。當我從本地作用域調用一個函數,它改變了$ scope變量的內容時,這不會影響DOM。在我的示例中,我向$ scope.customers列表中添加了一個新元素,並且這不會觸發ngRepeat,因此在渲染ngRepeat項目的位置時,DOM的這一部分不會受到影響。帶隔離作用域的Angularjs指令不會觸發指令外的DOM更改

指令代碼:

function addItem() { 
    scope.add(); 
     items.push({ 
     name: 'New Directive Customer' 
    }); 
    scope.$broadcast("refresh"); 
    render(); 
} 
... 
return { 
    restrict: 'EA', 
    scope: { 
     datasource: '=', 
     add: '&', 
    }, 
    link: link 
}; 

本地功能代碼:

$scope.addCustomer = function() { 
    counter++; 
    $scope.customers.push({ 
     name: 'New Customer' + counter, 
     street: counter + ' Cedar Point St.' 
    }); 

    alert($scope.customers.length); 
}; 

DOM ngRepeat部分:

<isolate-scope-with-controller datasource="customers" add="addCustomer()"></isolate-scope-with-controller> 
<hr /> 
<div> 
    <ul> 
     <li ng-repeat="customer in customers">{{customer.name}}</li> 
    </ul> 
</div> 

alert()將顯示該$scope.customers是每一個點擊按鈕後做大,但ngRepeat不能在DOM上工作。

的完整代碼: http://plnkr.co/edit/8tUzKbKxK0twJsB6i104

我的問題是,這是可能觸發從這種指令莫名其妙的DOM變化?

在此先感謝

回答

1

你plunkr只在指令的點擊回調消除對event.srcElement.id在檢查後爲我工作。

function addItem() { 
     //Call external function passed in with & 
     scope.add(); 

     //Add new customer to the local collection 
     items.push({ 
      name: 'New Directive Customer' 
     }); 


     scope.$broadcast("refresh"); 
     render(); 
    } 

在你必須使用$範圍控制器$申請進行更改出現在模板:

$scope.addCustomer = function() { 
     $scope.$apply(function(){ 
     counter++; 
     $scope.customers.push({ 
      name: 'New Customer' + counter, 
      street: counter + ' Cedar Point St.' 
     }); 

    }); 

http://plnkr.co/edit/lGmGiPIqEm2AA8cngkHz?p=preview

+0

在Chrome的代碼爲我工作。但是在$ scope的問題中,$ apply()解決了我的問題。非常感謝。 – MontyX