指令中的 scope.$watch 在 AJAX 请求后没有被调用 [英] scope.$watch in a directive isn't being called after AJAX request

查看:26
本文介绍了指令中的 scope.$watch 在 AJAX 请求后没有被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下指令:

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" />

当指令第一次初始化时,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 );
}

这只会在初始化指令时调用一次,然后值为空.当通过ajax(来自$http.get)检索值时,不会再次调用此监视函数.但是,在我显示 {{someField}} 的页面的其他部分,该值会在获取 ajax 请求时更新.所以我认为问题与在 ajax 请求之后执行 $scope.apply() 无关.

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 在控制器中分配.代码如下:

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() 并返回它的promise.在上面的代码中,调用了 load 方法来设置 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.

推荐答案

$watch 需要一个可以是函数或字符串的表达式.因此,如果您将其更改为

$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.

这篇关于指令中的 scope.$watch 在 AJAX 请求后没有被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆