简体   繁体   English

在AngularJS中,如何将$ scope传递给作用域?

[英]In AngularJS, how does $scope get passed to scope?

I'm a bit confused with the use of $scope in controllers and of scope in directives. 我在控制器和在指令范围内使用$范围的有点糊涂了。 Please verify if my understanding is correct (and also provide some alternative ways how to do this). 请验证我的理解是否正确(并提供一些替代方法来实现此目的)。

Let's say I have an html: 假设我有一个html:

<div ng-controller="app1_Ctrl">
    .
    .
    .
    <input type="text" ng-model="value"/>
    <input type="checkbox" />
    <button ng-click="submit()"></button>

</div>

And my main.js 还有我的main.js

(function() {

   angular.module('mainApp', ['app1']);

})();

And my app1 looks like this (based on official AngularJS documentation here ) 我的app1看起来像这样(基于此处的 AngularJS官方文档)

(function() {

    var app = angular.module('app1', []);

    app.controller('app1_Ctrl', ["$scope", function($scope) {
        .
        .
        .
    }]);

    app.directive('app1_Dir1', [function() {

        function link(scope, element, attr) {

            scope.$watch(attr.someAttrOfCheckBox, function() {
                // some logic here
            });

            function submit() {
                // some logic here
            }


        }

        return link;

     }]);

})();

How does $scope.value passed in scope in directive so that I can do some manipulations there? $ scope.value如何在指令的范围内传递,以便在那里进行一些操作? Will ng-click fire the function submit() in the directive link? ng-click是否会在指令链接中触发函数commit()? Is it correct to use scope.$watch to listen for an action (ticked or unticked of course) in checkbox element? 使用scope。$ watch侦听复选框元素中的动作(当然是勾选或取消勾选)是否正确?

Many thanks to those who can explain. 非常感谢那些可以解释的人。

By default, directive scope is controller $scope; 默认情况下,指令范围是控制器$ scope; but it means the directive is directly dependent on your controller and you need a different controller for each instance of the directive you want to use. 但这意味着指令直接取决于您的控制器,并且您要使用的指令的每个实例都需要一个不同的控制器。 It is usually considered a best practice to isolate your directive scope and specifically define the variables you wish to pass it from your controller. 通常,最好的方法是隔离指令范围,并专门定义要从控制器传递给它的变量。 For this, you will need to add a scope statement to your directive : 为此,您将需要在指令中添加作用域语句:

scope {
   label :'@',
   context : '=',
   function : '&'
}

and update your view : 并更新您的视图:

<my-directive label="labelFromController" context="ctxtFromController" function="myFunction()" ></my-directive>

The symbols denote the kind of thing you wish to pass through : @ is for one-way binding (as a string in your directive), = is for two-way binding of an object (which enables the directive to update something in your controller), and & is for passing a function. 符号表示您希望通过的事物: @用于单向绑定(作为指令中的字符串), =用于对象的双向绑定(这使指令可以更新控制器中的某些内容) )和&用于传递函数。 There are a lot of additional options and subtleties that are best explained by the Angular doc https://docs.angularjs.org/guide/directive . Angular文档https://docs.angularjs.org/guide/directive可以最好地解释很多其他选项和细微之处。 There are also some nice tutorials out there (eg http://www.sitepoint.com/practical-guide-angularjs-directives/ ) 也有一些不错的教程(例如, http : //www.sitepoint.com/practical-guide-angularjs-directives/

  • Your submit() function is not attached to anything, so you won't be able to call if from your viewer. 您的commit()函数未附加任何内容,因此如果从查看器中调用,则将无法调用。 You need to define it as scope.submit = function() ... in your link function if you wish to access it. 如果要访问它,则需要在链接函数scope.submit = function() ...其定义为scope.submit = function() ...
  • You can use $watch for this kind of thing, but there are usually other more elegant ways to achieve this by leveraging the fact that angular already "watches" the variables it is aware of and monitors any changes he can (this can be an issue when some external service changes data for exemple, because angular cannot listen to events it is not made aware of). 您可以使用$ watch进行此类操作,但是通常还有其他更优雅的方法可以利用以下事实来实现这一点:angular已经“监视”了它所知道的变量并监视了他可以进行的任何更改(这可能是一个问题例如,当某些外部服务更改数据时,由于angular无法侦听事件,因此它没有被意识到)。 Here, you can probably simply associate the ng-model directive to your input checkbox to store its true/fale (checked/unchecked) value, and the ng-change or ng-click directives to act on it. 在这里,您可以简单地将ng-model指令与输入复选框关联起来,以存储其真实/真实(选中/未选中)值,然后使用ng-change或ng-click指令对其进行操作。 The optimal solution will mostly depend on the exact nature of your business logic. 最佳解决方案将主要取决于您的业务逻辑的确切性质。

Some additional thoughts : 其他一些想法:

  • The HTML insides of your directive should be packaged in an inline template field, or in a separate HTML file referenced by the templateUrl field in your directive. 你的指令的HTML内部应包装在一个内联template场,或在引用的一个单独的HTML文件templateUrl场在你的指令。
  • In your HTML code above, your directive is not referenced anywhere. 在上面的HTML代码中,您的指令未在任何地方被引用。 It should be an element, attribute or class (and your directive definition should reflect the way it can be called, with the restrict field). 它应该是元素,属性或类(您的指令定义应反映使用restrict字段进行调用的方式)。 Maybe you have omitted the line containing the directive HTML, but as it stands, your directive doesn't do anything. 也许您已经省略了包含指令HTML的行,但就目前而言,您的指令没有执行任何操作。
  • To my knowledge, you don't need to return link. 据我所知,您不需要返回链接。 Think of it as the "body" of your directive, where you define the variables and functions you will call in the HTML. 将其视为指令的“主体”,您可以在其中定义将在HTML中调用的变量和函数。
  • Your directive doesn't actually need HTML code and the above thoughts might be irrelevant if you are going in a different direction, but encapsulating some kind of view behaviour that you want to reuse is probably the most common use of directives. 您的指令实际上并不需要 HTML代码,并且如果您朝不同的方向进行操作,上述想法可能无关紧要,但是封装要重用的某种视图行为可能是指令最常见的用法。

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

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