我對於AngularJS指令中'模板'呈現時有點困惑。請參見下面的代碼片段:AngularJS指令在模板呈現時
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js" data-semver="1.1.5"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<example-directive name="{{name}}"></example-directive>
</body>
</html>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'First ONE ';
});
app.directive('exampleDirective', function() {
return {
restrict: 'E',
scope: {
name: "@"
},
template: '<p>Hello {{name}}!</p>',
controller: function($scope, $element){
$scope.name = $scope.name + "Second ";
$scope.name2 = $scope.name + "Second ";
},
link: function(scope, el, attr) {
scope.name = scope.name + "Third ";
$scope.name2 = $scope.name + "Second ";
}
}
})
它顯示「Hello首先一號」,這意味着沒有在控制器和鏈接功能的第一條語句的改變的值名稱範圍內,或者更改未反映在模板中。
但是,如果我改變了指令
template: '<p>Hello {{name2}}!</p>'
或變「名」,以雙向使用「=」,而不是結合「@」
它呈現「你好第一個秒秒!」如預期。
的plunker是here
所以它意味着一個雙向綁定,在模板範圍VAR之前被渲染器和鏈接功能在踢?
我已經在我的問題提到,轉變爲雙向綁定將使它發揮作用。只是想知道背後的原因。 – MichaelYu 2014-12-03 09:22:42
檢查編輯答案。 – 2014-12-03 10:09:08
我認爲這是相當自我解釋現在,謝謝 – MichaelYu 2014-12-08 08:52:54