注意:当我找到更好的解决方案时,我会更新此答案。只要它们保持相关,我也会保留旧答案以供将来参考。最新最好的答案是第一位的。
更好的答案:
angularjs 中的指令非常强大,但需要时间来理解它们背后的进程。
在创建指令时,angularjs 允许您创建一个隔离范围,其中包含一些与父范围的绑定。这些绑定由您在 DOM 中附加元素的 属性 以及如何在 指令定义对象 中定义 scope 属性来指定。
您可以在范围内定义 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>
您应该注意的一件事是,如果您想设置值字符串,您应该将它用引号括起来。 (见第三个输入)
这里是小提琴: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
在当前范围内执行返回结果的表达式。表达式中的任何异常都会传播(未捕获)。这在评估角度表达式时很有用。