在指令范围内。$表没有被AJAX请求后调用 [英] scope.$watch in a directive isn't being called after AJAX request
问题描述
我有以下指令:
MyApp.directive('myFilter', ['$filter','$rootScope',
function($filter, $rootScope)
{
var dir = {};
dir.restrict = 'E';
dir.templateUrl = 'views/myFilter.html';
dir.replace = true;
dir.scope =
{
name: '@',
model: '=',
};
dir.link = function(scope,el,attrs)
{
//stuff here
}
return dir;
}]);
下面是我如何调用它:
<my-filter model="someField" name="abcd" />
在该指令首次initalized,在 someField
是空的。以后,它是通过AJAX检索,且其值被填充在
When the directive is first initalized, the someField
is empty. Later on, it is retrieved via ajax, and its value is filled in.
问题是,我怎么能观看 someField
的值更新?当我做这从连接方式:
Question is, how can I watch for the value of someField
to be updated? When I do this from the link method:
scope.$watch(scope.model, function()
{
console.log( "changed, new val: ", scope.model );
}
initalizing指令时,这只是调用一次,然后该值是空的。当该值通过AJAX检索(从 $ http.get
),这款手表的功能不再调用。然而,在我显示页面的其他部分 {{} someField}
,该值会更新时,Ajax请求被取出。因此,我不认为这个问题有做 $ scope.apply()
后Ajax请求。
This is only called once, when initalizing the directive, and the value then is empty. When the value is retrieved via ajax (from $http.get
), this watch function is not called again. However, in other parts of the page where I'm displaying {{someField}}
, that value DOES update when ajax request is fetched. So I don't think the problem has to do with doing $scope.apply()
after ajax request.
编辑: someField
被分配在控制器中。这里是code:
someField
is assigned in the controller. Here is the code:
MyApp.controller('myCtrl',
['$scope', '$rootScope', '$routeParams',
'ajax', '$filter',
function($scope, $rootScope, $routeParams, ajax, $filter)
{
var userId = parseInt( $routeParams.userId );
$scope.loaded = false;
$scope.someField = ""; //initalize with empty value
var load = function(data)
{
$scope.loaded = true;
$scope.someField = data.someField;
};
ajax.getUser(userId).success(load);
}
]);
该方法 ajax.getUser()
做了 $ http.get()
并返回其诺
。在上面的code时,负荷
方法被调用它设置的值 someField
。
The method ajax.getUser()
does a $http.get()
and returns its promise
. In the code above, the load
method is called which sets the value of someField
.
推荐答案
$观看
预计一个前pression这可以是一个函数或字符串。因此,它会工作,如果你将其更改为
$watch
expects an expression that can be either a function or a string. So, it'll work if you change it to
scope.$watch('model', function() { ... });
或
scope.$watch(function() { return scope.model; }, function() { ... });
查看此的jsfiddle 。
这篇关于在指令范围内。$表没有被AJAX请求后调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!