简体   繁体   English

控制器和指令中的角度范围问题

[英]Angular scope issue in a Controller and a Directive

I have the following in a controller: 我在控制器中具有以下内容:

 Restangular.all('foos').getList().then(
    function(foos) {
        $scope.foos = foos;
    });

In an HTML page, I am able to do the following: 在HTML页面中,我可以执行以下操作:

<div ng-repeat="foo in foos | orderBy:'fooName'">

I want to move the ng-repeat to a directive, so I have the following in a directive: 我想将ng-repeat移至指令,因此指令中包含以下内容:

app.directive('interactionFoos', function(){

return {
    restrict: 'A',
    scope : false,
    link: function($scope, $element, $attrs) {

        //console.log("*** size: " + $scope.foos.length);
    }
}

});

And in the HTML I will have: 在HTML中,我将拥有:

<div interaction-foos></div>

In the directive, I am getting undefined for $scope.foos. 在指令中,我对$ scope.foos不确定。 As a test, in the controller, I hard coded: $scope.test= 'foobar'. 作为测试,在控制器中,我进行了硬编码:$ scope.test ='foobar'。 Then, in the directive, I replaced the log line with the following and it printed 'foobar': 然后,在指令中,我将日志行替换为以下内容,并显示“ foobar”:

console.log("*** test: " + $scope.test);

I do not know why $scope.test is working as I expect, but $scope.foos is not? 我不知道为什么$ scope.test可以正常运行,但是$ scope.foos却不能正常工作?

I believe this is an Async issue as Restangular would run as a promise so foo would not be set when the directive link function runs. 我相信这是一个异步问题,因为Restangular将作为一个承诺运行,因此当指令链接函数运行时不会设置foo。 To get around this you need to add a watch to see when the scope has changed 为了解决这个问题,您需要添加手表以查看范围何时更改

$scope.$watch('foos', function(newValue, oldValue) { console.log(newValue, oldValue); }); $ scope。$ watch('foos',function(newValue,oldValue){console.log(newValue,oldValue);});

do something like this: 做这样的事情:

 angular.module("app", []) .controller("interactionCtrl", function($scope) { $scope.foos = ["A", "B", "C"]; }) .directive("interactionFoos", function() { return { restrict: 'A', scope: { foos: '=' }, link: function(scope, element, attrs) { alert(scope.foos.length); } }; }); 
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script> <div ng-app="app" ng-controller="interactionCtrl"> <div interaction-foos foos="foos"></div> </div> 

basically the foos in the directive binds to the foos that are exposed on the controller. 基本上,指令中的foo绑定到控制器上公开的foo。

also in your linking function don't use $ in the name of the function arguments, for example call the first argument scope instead of scope, because those arguments are not really injected to the link function (it's a regular function call, if you name the first argument bob it will still be equal to the scope) 在链接函数中也不要在函数参数的名称中使用$,例如,调用第一个参数作用域而不是作用域,因为那些参数并没有真正注入到链接函数中(如果您命名,则是常规函数调用)第一个参数bob仍将等于范围)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM