Javascript 如何在指令的链接函数中对绑定对象作出反应
在我的web项目中,我正在编写一个指令,该指令必须对从服务器获取的数据做出反应。指令必须尽可能通用,这就是我通过控制器获取数据的原因。下一段代码是一个简化的伪示例,我希望它能够工作: 首先,我的控制器:Javascript 如何在指令的链接函数中对绑定对象作出反应,javascript,angularjs,Javascript,Angularjs,在我的web项目中,我正在编写一个指令,该指令必须对从服务器获取的数据做出反应。指令必须尽可能通用,这就是我通过控制器获取数据的原因。下一段代码是一个简化的伪示例,我希望它能够工作: 首先,我的控制器: AnApp.controller("myController", function($scope, $http){ $scope.theObject = {}; $scope.initialize = function(){ $http.get("url").s
AnApp.controller("myController", function($scope, $http){
$scope.theObject = {};
$scope.initialize = function(){
$http.get("url").success(function(returnObject){
$scope.theObject = returnObject;
});
};
});
该指令:
AnApp.directive("myDirective", function() {
return {
restrict: "A",
scope: {
theObject: '@'
},
link: function(scope, element, attributes) {
//What do I have to do here to read my attributes when they change in the controller?
}
});
以及html:
<div data-ng-controller="myController">
<div data-my-directive="" data-the-object="theObject"></div>
</div>
我想做的是,当对象发生变化时,链接函数中会发生对变化的反应。到目前为止,我尝试了$parse、$observe、scope.$watch,但都不起作用。他们都返回了字符串“theObject”或未定义。当从服务器检索到对象或数组并将其放在作用域中时,如何到达该对象或数组?双向=
(而不是@
)绑定可能适合您的目的,可以通过这种方式查看对模型的更改。当您使用@
时,它实际上是按原样绑定文本,为此,您可能必须将其绑定为{{theObject}
,并注意更改(但您可能必须将JSON解析回对象)
如果您只需要一次初始化,那么:-您可以在手表初始化后卸下它…谢谢。对=的更改使作用域$watch起作用。我认为@是一个单向绑定,这就是为什么我要使用它。由于数据仅在控制器中更改,而在我的指令中从未更改,因此我怀疑@就足够了。但显然,它的工作原理和我想的不同。@Cornelis,不客气。你可以使用
@
,但正如我在回答中提到的,你需要用不同的方式来做。
AnApp.directive("myDirective", function() {
return {
restrict: "A",
scope: {
theObject: '='
},
link: function(scope, element, attributes) {
var unwatcher = scope.$watch('theObject', function(v){
if(angular.isDefined(v)){
unwatcher(); //May be unwatch if you do not want to watch it anymore.
//got the value do something
}
//This will react to changes now.
});
}
});