我刚刚从KnockoutJS切换到AngularJS,在AngularJS中找不到KnockoutJS的"with“数据绑定。
下面是KnockoutJS中的一段代码。"with“绑定创建一个新的绑定上下文,以便在指定对象的上下文中绑定后代元素。
<h1 data-bind="text: city"> </h1>
<p data-bind="with: coords">
Latitude: <span data-bind="text: latitude"> </span>,
Longitude: <span data-bind="text: longitude"> </span>
</p>
<script type="text/javascript">
ko.applyBindings({
city: "London",
coords: {
latitude: 51.5001524,
longitude: -0.1262362
}
});
</script>
AngularJS有没有上下文之类的东西?
发布于 2013-06-25 23:45:19
不像我所知道的那样..这是我能做的最好的事情:
<h1>{{city}}</h1>
<p ng-repeat="c in [coords.or.possibly.deeper.in.tree]">
Latitude: {{c.latitude}},
Longitude: {{c.longitude}}
</p>
发布于 2014-07-21 15:27:59
创建一个循环通过源对象的自定义指令,并在该指令的作用域上创建相应的属性,这些属性是对源对象的getter/setter引用。
看看这个plunker。
指令模块:
angular.module('koWith', [])
.directive('koWith', function () {
return {
controller: function ($scope, $attrs) {
var withObj = $scope.$parent[$attrs.ngWith];
function getter(prop) {
return this[prop];
}
function setter(val, prop) {
this[prop] = val;
}
for (var prop in withObj) {
if (withObj.hasOwnProperty(prop)) {
Object.defineProperty($scope, prop, {
enumerable: true,
configurable: true,
get: getter.bind(withObj, prop),
set: setter.bind(withObj, prop)
});
}
}
},
restrict: 'A',
scope: true
};
});
应用程序模块:
angular.module('myApp', [])
.controller('myController', function ($scope) {
$scope.customer = {
name: "Timmeh",
address: {
address1: "12 S Street",
address2: "",
city: "South Park",
state: "CO",
zipCode: "80440"
}
};
});
html:
<div ko-with="customer">
<h2>{{name}}</h2>
<div ko-with="address">
{{address1}}<br>
{{address2}}<br>
{{city}}, {{state}} {{zipCode}}
</div>
</div>
解释
在KnockoutJS中,绑定将bindingContext和数据分开,因此创建with
绑定很简单,因为它只需要从当前的子bindingContext创建一个新的子and,并使用with
对象作为其数据值。
在AngularJS中,指令的作用域基本上是将bindingContext和数据对象合二为一。创建新的作用域时,为了获得with
-like行为,必须将with
对象的属性引用到新创建的作用域对象上。
发布于 2015-03-07 05:59:06
这是一个基于@nwayve的解决方案,但它支持koWith中的表达式,并监视在koWith中指定的属性/表达式的更新:
.directive('koWith', function () {
return {
restrict: 'A',
scope: true,
controller: function ($scope, $attrs, $parse) {
var ScopePropertyDesc = function (prop) {
var self = this;
self.propName = prop;
self.parsed = $parse(prop);
self.enumerable = true;
self.configurable = true;
//self.writable = true;
self.get = function () {
var withObj = $scope.$parent[$attrs.koWith];
var res = self.parsed($scope.$parent, withObj);
return res;
};
self.set = function (newValue) {
var withObj = $scope.$parent[$attrs.koWith];
self.parsed.assign(withObj, newValue);
};
};
$scope.$parent.$watch($attrs.koWith, function (oldVal, newVal) {
var withObj = $scope.$parent[$attrs.koWith];
(function copyPropertiesToScope(withObj) {
for (var prop in withObj) {
if (withObj.hasOwnProperty(prop)) {
Object.defineProperty($scope, prop, new ScopePropertyDesc(prop));
}
};
})(withObj);
});
}
};
});
https://stackoverflow.com/questions/17300814
复制相似问题