注意:より良い解決策を見つけたら、この回答を更新します。また、それらが関連している限り、将来の参考のために古い回答を保持します。最新のベスト アンサーが最初に表示されます。
より良い答え:
angularjs のディレクティブは非常に強力ですが、背後にあるプロセスを理解するには時間がかかります。
ディレクティブを作成している間、angularjs を使用すると、親スコープへのバインディングを使用して分離スコープを作成できます。これらのバインディングは、DOM で要素にアタッチする属性と、ディレクティブ定義オブジェクトでスコーププロパティを定義する方法によって指定されます。
スコープで定義できるバインド オプションには 3 つのタイプがあり、それらをプレフィックス関連の属性として記述します。
angular.module("myApp", []).directive("myDirective", function () {
return {
restrict: "A",
scope: {
text: "@myText",
twoWayBind: "=myTwoWayBind",
oneWayBind: "&myOneWayBind"
}
};
}).controller("myController", function ($scope) {
$scope.foo = {name: "Umur"};
$scope.bar = "qwe";
});
HTML
<div ng-controller="myController">
<div my-directive my-text="hello {{ bar }}" my-two-way-bind="foo" my-one-way-bind="bar">
</div>
</div>
その場合、ディレクティブのスコープで (関数またはコントローラーのリンクに関係なく)、次のようにこれらのプロパティにアクセスできます。
/* Directive scope */
in: $scope.text
out: "hello qwe"
// this would automatically update the changes of value in digest
// this is always string as dom attributes values are always strings
in: $scope.twoWayBind
out: {name:"Umur"}
// this would automatically update the changes of value in digest
// changes in this will be reflected in parent scope
// in directive's scope
in: $scope.twoWayBind.name = "John"
//in parent scope
in: $scope.foo.name
out: "John"
in: $scope.oneWayBind() // notice the function call, this binding is read only
out: "qwe"
// any changes here will not reflect in parent, as this only a getter .
「まだ大丈夫です」 答え:
この回答は受け入れられましたが、いくつかの問題があるため、より良いものに更新します。どうやら、$parse
現在のスコープのプロパティにないサービスです。つまり、角度式のみを取り、スコープに到達できません。
{{
、}}
式は angularjs の開始中にコンパイルされます。つまり、ディレクティブpostlink
メソッドでそれらにアクセスしようとすると、それらは既にコンパイルされています。(すでにディレクティブになっています){{1+1}}
。2
これはあなたが使いたい方法です:
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function ($parse) {
return function (scope, element, attr) {
element.val("value=" + $parse(attr.myDirective)(scope));
};
});
function MyCtrl($scope) {
$scope.aaa = 3432;
}
.
<div ng-controller="MyCtrl">
<input my-directive="123">
<input my-directive="1+1">
<input my-directive="'1+1'">
<input my-directive="aaa">
</div>
ここで注意すべきことの 1 つは、値の文字列を設定する場合は、引用符で囲む必要があるということです。(3 番目の入力を参照)
ここで遊ぶフィドルは次のとおりです:http://jsfiddle.net/neuTA/6/
古い答え:
私のように誤解される可能性のある人のためにこれを削除するつもりはありません。使用$eval
は正しい方法で完全に問題ありませんが$parse
、動作が異なります。ほとんどの場合、これを使用する必要はないでしょう。
それを行う方法は、もう一度、を使用することscope.$eval
です。角度式をコンパイルするだけでなく、現在のスコープのプロパティにもアクセスできます。
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function () {
return function (scope, element, attr) {
element.val("value = "+ scope.$eval(attr.value));
}
});
function MyCtrl($scope) {
}
あなたが欠けているのは$eval
.
http://docs.angularjs.org/api/ng.$rootScope.Scope#$eval
結果を返す現在のスコープで式を実行します。式内のすべての例外が伝搬されます (キャッチされません)。これは、角度式を評価するときに役立ちます。