2014-12-03 86 views
2

我對於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之前被渲染器和鏈接功能在踢?

回答

1

只要改變這一點:

<example-directive name="{{name}}"></example-directive> 

這樣:

<example-directive name="name"></example-directive> 

這:

scope: { 
    name: "@" 
}, 

這樣:

scope: { 
    name: "=" 
}, 

它會工作。

更新:

對不起,因爲沒有閱讀整個問題。 這裏是什麼在docs

@或@attr - 局部範圍的屬性綁定到DOM屬性的值。結果總是一個字符串,因爲DOM屬性是字符串。如果未指定attr名稱,則假定屬性名稱與本地名稱相同。給定範圍的小部件定義:{localName:'@ myAttr'},那麼小部件範圍屬性localName將反映hello {{name}}的內插值。由於名稱屬性發生變化,widget屬性的localName屬性也會發生變化。該名稱是從父作用域(不是組件作用域)讀取的。

通知的最後一部分:The name is read from the parent scope (not component scope)

+0

我已經在我的問題提到,轉變爲雙向綁定將使它發揮作用。只是想知道背後的原因。 – MichaelYu 2014-12-03 09:22:42

+0

檢查編輯答案。 – 2014-12-03 10:09:08

+0

我認爲這是相當自我解釋現在,謝謝 – MichaelYu 2014-12-08 08:52:54