Javascript 每次加载页面时都会调用指令,为什么?
我在AngularJS中处理一些指令,代码如下:Javascript 每次加载页面时都会调用指令,为什么?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我在AngularJS中处理一些指令,代码如下: app.directive('country', ['$http', function($http) { return { restrict: "C", link: function(scope, element, attrs) { $http.get(Routing.generate('countries')).success(function(da
app.directive('country', ['$http', function($http) {
return {
restrict: "C",
link: function(scope, element, attrs) {
$http.get(Routing.generate('countries')).success(function(data) {
if (data.message) {
scope.message = data.message;
} else {
scope.countries = data.entities;
}
}).error(function(data, status, headers, config) {
if (status == '500') {
scope.message = "No hay conexión con el servidor.";
}
});
}
};
}]);
app.directive('state', ['$http', '$parse', function($http, $parse) {
return {
restrict: "C",
scope: {
country: "="
},
link: function(scope, element, attrs) {
scope.$watch(attrs.trigger, function() {
console.log("I'm in");
if ($parse(attrs.trigger) !== undefined) {
states = $parse(attrs.statetrigger)(scope);
states = {};
$http.get(Routing.generate('states') + '/' + $parse('scope.' + attrs.trigger).iso_country).success(function(data) {
if (data.message) {
scope.message = data.message;
} else {
scope.states = data.entities;
}
}).error(function(data, status, headers, config) {
if (status == '500') {
scope.message = "No hay conexión con el servidor.";
}
});
}
});
}
};
}]);
app.directive('city', ['$http', '$parse', function($http, $parse) {
return {
restrict: "C",
link: function(scope, element, attrs) {
scope.$watch(attrs.statetrigger, function() {
if ($parse('scope.' + attrs.countrytrigger) !== undefined && $parse('scope.' + attrs.statetrigger) !== undefined) {
$http.get(Routing.generate('cities') + '/' + $parse('scope.' + attrs.countrytrigger).iso_country + '/' + $parse('scope.' + attrs.statetrigger).state).success(function(data) {
if (data.message) {
scope.message = data.message;
} else {
scope.cities = data.entities;
}
}).error(function(data, status, headers, config) {
if (status == '500') {
scope.message = "No hay conexión con el servidor.";
}
});
}
});
}
};
}]);
出于某种原因,我不知道,任何时候页面加载都会调用这两个指令并且不知道为什么,有人能给我一些提示吗?我离开了,因为一张照片能说上千个字
看你去理解angular js的执行吧!启动web应用程序时,angular js会在内存中加载对指令和控制器等的所有引用,这是第一次调用发生时,但指令等不会执行 现在在html中,您必须使用控制器和指令,因此angular js编译器将html世界未知的自定义指令(如ng repeat、ng show等)替换为普通html代码,并编写javascript代码(称为$watches),以便您的模型自动绑定到视图。。i、 e.双向数据绑定,基本上只是一个javascript代码,当你更新一个模型时会运行。不同的是你不必显式地编写代码,它会为你做到这一点
因此,当页面加载时,HTML中的任何指令都将被调用,以便angular知道如何处理它您在index.HTML页面中调用了这些指令吗?@BKM,no不会在
index.HTML
页面中调用