我的代码如下:
one_time.js
var sample = angular.module('sample', []);
sample.controller('OneTimeController', function () {
this.name = 'John';
this.blah = 'sdflk';
});
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript" src="one_time.js"></script>
</head>
<body ng-app="sample">
<div ng-controller="OneTimeController as test">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="test.name" value="John"></p>
<p ng-bind="test.name"></p>
<p ng-bind="::test.name"></p>
<p ng-if="test.name && test.blah">testing</p> <!-- works perfectly-->
<p ng-if="::test.name && test.blah">testing with first expression as one time binded</p> <!-- works but the second property is not one time binded-->
<p ng-if="::test.name && ::test.blah">testing with one time bind</p><!-- doesn't work throws syntax error-->
</div>
</body>
</html>
我试图显示一个带有 ng-if 条件的<p>
标记,在该条件下我希望 name 属性一次性绑定。 我已经知道它不会改变,所以也想尝试在 ng-if 中进行一次绑定。 当我不使用一次绑定或者在这种情况下我只对第一个表达式使用一次绑定时它完美地工作<p ng-if="::test.name && test.blah">testing with first expression as one time binded</p>
,但是当我尝试在多个表达式中使用一次绑定时一个守卫运算符,它以语法错误的形式抛出我的错误:
Error: [$parse:syntax] Syntax Error: Token ':' not a primary expression at column 14 of the expression [test.name && ::test.blah && ::test.blah] starting at [::test.blah && ::test.blah].
http://errors.angularjs.org/1.3.14/$parse/syntax?
这是错误还是真正的语法错误? 我正在使用 angularjs 版本 1.3.14。
我认为您应该将()
用于带有表达式的按时绑定,例如: <p ng-if="::(test.name && test.blah)">testing with first expression as one time binded</p>
@piernik谢谢,就像一个魅力。 我正在尝试(::test.name) && (::test.blah)
但似乎第一个::
激活了一次绑定。 :+1:
一次性绑定 (::) 适用于 ng-if 中使用的所有表达式。
<p ng-if="::test.name && test.blah"> is same as <p ng-if="::(test.name && test.blah)">
不幸的是,我们不能在 angular js 中的单个表达式中混合一次绑定和单向绑定表达式。
最有用的评论
我认为您应该将
()
用于带有表达式的按时绑定,例如:<p ng-if="::(test.name && test.blah)">testing with first expression as one time binded</p>