Angular指令和http,模型不起作用
Angular指令和http,模型不起作用
当在控制器中设置$scope.instrumentNames
,像提供的代码中一样,它起作用。
当在HTTP的success
函数中设置$scope.instrumentNames
时,它不起作用。
http
函数返回的数据是一个数组。
Console.log(data)//["Guitar", "Bass", "Violin"] Console.log($scope.instrumentNames) //["Guitar", "Bass", "Violin"]
控制器
app.controller("PrivateProfileController", ["$scope", "$http", "$routeParams", function( $scope, $http, $routeParams ) { $scope.instrumentNames = ["Guitar", "Bass", "Violin"];//起作用! function loadInstrumentNames(){ $http({ url: '/Instrument/getInstrumentsName', method: "GET" }).success(function(data){ //data = ["Guitar", "Bass", "Violin"] $scope.instrumentNames = data;//不起作用 }); } loadInstrumentNames() }] );
指令
app.directive('autoComplete', [function($timeout) { return { restrict: "A", link : function(scope, element, attrs) { element.autocomplete({ source: scope[attrs.uiItems], select: function() { $timeout(function() { element.trigger('input'); }, 200); } }); } }; }]);
模板
好像指令在http success
完成之前被调用。我被这个问题困扰着,任何帮助或建议将非常感激!
谢谢
Angular指令和http,模型不起作用的问题是由于指令在http请求成功完成之前被调用导致的。需要在数据返回之前等待才能执行自动完成功能。可以通过使用$watch来实现。代码如下:
app.directive('autoComplete', [function($timeout) { return { restrict: "A", link: function(scope, element, attrs) { scope.$watch(attrs.uiItems, function(uiItems) { if (uiItems) { element.autocomplete({ source: scope[attrs.uiItems], select: function() { $timeout(function() { element.trigger('input'); }, 200); } }); } }); } }; }]);
为了让它只运行一次,可以将$watch调用的返回值赋给一个变量,并在最后调用该函数,这样$watch就不会再执行了。代码如下:
var unwatch = scope.$watch(attrs.uiItems, function(uiItems) { if (uiItems) { //处理数据的代码 unwatch(); } });
在stackoverflow的链接中提到了更多相关的问题和解决方法。如果使用var listener = $scope.$watch等方式,可以通过listener()来自动取消$watch。
通过以上的修改,问题得到了解决。