我使用“scope”创建了一个绑定的指令.在某些情况下,我想绑定一个常量对象.例如,使用
HTML:
<div ng-controller="Ctrl"> <greeting person="{firstName: 'Bob',lastName: 'Jones'}"></greeting> </div>
和JavaScript:
var app = angular.module('myApp',[]); app.controller("Ctrl",function($scope) { }); app.directive("greeting",function () { return { restrict: "E",replace: true,scope: { person: "=" },template: '<p>Hello {{person.firstName}} {{person.lastName}}</p>' }; });
虽然这样,它也会导致JavaScript错误:
Error: 10 $digest() iterations reached. Aborting!
这是我想出的解决方案,基于@ sh0ber的答案:
实现自定义链接功能.如果属性是有效的JSON,那么它是一个常量值,所以我们只评估一次.否则,正常观察和更新值(换句话说,尝试作为=绑定的行为).范围需要设置为true,以确保分配的值仅影响该指令的此实例.
HTML:
<div ng-controller="Ctrl"> <greeting person='{"firstName": "Bob","lastName": "Jones"}'></greeting> <greeting person="jim"></greeting> </div>
JavaScript的:
var app = angular.module('myApp',function($scope) { $scope.jim = {firstName: 'Jim',lastName: "Bloggs"}; }); app.directive("greeting",scope: true,link: function(scope,elements,attrs) { try { scope.person = JSON.parse(attrs.person); } catch (e) { scope.$watch(function() { return scope.$parent.$eval(attrs.person); },function(newValue,oldValue) { scope.person = newValue; }); } },template: '<p>Hello {{person.firstName}} {{person.lastName}}</p>' }; });