[英]Angular - changes to directive controller's scope aren't reflected in view
對我的范圍變量foo
更改正在html中更新。 當該值在指令的控制器范圍內更改時,它不會在html中更新。
我需要怎么做才能使其更新?
我有一個簡單的例子 :
app.js
var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.foo = 99;
$scope.changeValue = function() {
$scope.foo = $scope.foo + 1;
}
});
app.directive('d1', function(){
return {
restrict: 'E',
scope: {
theFoo: '='
},
templateUrl: 'd1.html',
controller: 'd1Ctrl',
}
});
app.controller('d1Ctrl', function($scope) {
$scope.test = $scope.theFoo;
});
d1.html
<div>
<p>The value of foo is '{{theFoo}}'.</p>
<p>The value of test is '{{test}}'.</p>
</div>
內部index.html
<d1 the-foo='foo'>
</d1>
<button ng-click='changeValue()'>change value</button>
因此,總而言之, {{theFoo}}
正在更新,而{{test}}
沒有更新。 為什么?
如果在鏈接控制器時確實設置了該值,則控制器中包含的代碼只會初始化為該值。 隨后的任何更改都將無效。
如果要綁定任何后續更改,則需要在控制器或鏈接函數中設置$ watch語句。
$scope.$watch( 'theFoo', function(val){ $scope.test = val; })
更新plunker - http://plnkr.co/edit/eWoPutIJrwxZj9XJu6QG?p=preview
原因是$scope.foo
值是原始值。
在指令控制器中,僅在控制器初始化時分配一次$scope.test
。 基元沒有對象的繼承方式,因此在初始分配后沒有任何東西會改變$scope.test
如果您使用的對象,而不是通過在...繼承會生效,你會看到變化......否則你就需要看$scope.theFoo
並做更新$scope.test
自己
在這里,你已經分離指令的范圍,所以test
是不可見的d1.html
,如果您需要更改test
與沿theFoo
必須先讓它通過該指令可見
app.directive('d1', function(){
return {
restrict: 'E',
scope: {
theFoo: '=',
test : '=' //getting test as well
},
templateUrl: 'd1.html',
controller: 'd1Ctrl',
}
});
在index.html中,您應該通過<d1 the-foo='foo' test='foo'></d1>
將值傳遞給測試
在上面的代碼中,您的控制器沒什么用,即使沒有此部分controller: 'd1Ctrl'
,代碼也可以正常工作controller: 'd1Ctrl'
。 在此示例中,您不必使用$watch
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.