[英]How to render scope variable on template in Angular directive
[更新]事實證明,如果我使用“ @”作為范圍變量,則在渲染模板時將以異步方式使用它(我仍然不知道為什么和方式),順序將是順從的->控制器-> pre-> post->觀察,奇怪的是直到POST階段,scope.data仍然是對象,但是在觀察中,它突然變成了字符串, 有人可以給我一些有關為什么發生這種情況的幫助(例如當模板獲取時)數據綁定到它)?
var app = angular.module("vp", []);
app
.controller("main", function($scope){
$scope.data = ["1", "2"];
})
.directive("chartBuilder", function(){
return {
restrict: "AE",
scope: {
data: "@data"
},
controller: function($scope){
console.log($scope.data);
$scope.data = JSON.parse($scope.data);
},
template: '<div><input ng-repeat="d in data track by $index" ng-model="data[$index]" /></div>',
compile: function(EL, attrs){
console.log(EL);
return {
pre: function(scope, EL, attrs){
console.log(scope.data);
},
post: function(scope, EL, attrs){
// link: function(scope, EL, attrs){
console.log(scope.data);
attrs.$observe("data", function(d){
console.log(d);
scope.data = JSON.parse(scope.data);
console.log(d);
})
}
}
}
};
});
所有:
我對Angular指令還很陌生,說我有一個可以從父范圍接受attr的指令:
<html ng-app="vp">
<head>
<title></title>
</head>
<body ng-controller="main">
<input ng-repeat="d in data track by $index" ng-model="data[$index]" />
<chart-builder data={{data}}></chart-builder>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("vp", []);
app
.controller("main", function($scope){
$scope.data = ["1", "2"];
})
.directive("chartBuilder", function(){
return {
restrict: "AE",
scope: {
data: "@"
},
controller: function($scope){
$scope.data = JSON.parse($scope.data);
},
template: '<div><input ng-repeat="d in data track by $index" ng-model="data[$index]" /></div>',
link: function(scope, EL, attrs){
}
};
});
</script>
</body>
</html>
注意,我在指令中使用“ @”,原因是我想設置如下邏輯 :
父作用域可以影響偽指令中的值,但是在偽指令中,只允許從父作用域復制數據,並且內部的任何更改都不能反映到父作用域。
因此,例如,初始父范圍數據為[1,2],因此該指令會將其作為字符串(因為@)獲取,並在控制器中將其轉換為對象,然后在模板上呈現。
但問題是:
當在template上呈現指令時,指令中的數據仍然是字符串 ,我想知道為什么JSON.parse不起作用(在指令的控制器中,它確實有效,但是當綁定到模板時,它仍然為string)
謝謝
傳遞數組引用要簡單得多:
<chart-builder data="data"></chart-builder>
JS
app
.controller("main", function($scope){
$scope.data = ["1", "2"];
})
.directive("chartBuilder", function(){
return {
restrict: "AE",
scope: {
data: "="
},
controller: function($scope){
console.log($scope.data)// array not string ["1", "2"]
},
template: '...',
link: function(scope, EL, attrs){
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.