Scope This object in angular is very important, can say to want to learn angularjs, skilled use of the scope of the basic skills, the following describes the scope of several binding strategies.
1, @: Pass the current attribute as a string. You can also bind the value of scope from the outer layer and insert {{}} in the property value. Here is the code.
<! DOCTYPE html>
Controller code
var mymodule=angular.module ("MyModule", []); Mymodule.controller (' Myctrl ', [' $scope ', function ($scope) { $ Scope.ctrlflavor= "88888";}]) Mymodule.directive ("Drink", function () { return{ restrict: ' AE ', scope:{ ZK: ' @ ' }, Template: "<div>{{zk}}</div>" })
There is a ZK attribute in the directive drink, and the scope of its upper Div has a ctrlflavor attribute, the example above is that the value of scope in the upper Div is bound to the ZK attribute of the lower instruction drink.
2, "=": two-way binding with attributes in parent scope
The code in the HTML, I shortened it, and the same as above
<div ng-controller= "Myctrl" > Ctrl: <br> <input type= "text" ng-model= "Ctrlflavor" > <br> Directive: <br> <drink zk= "Ctrlflavor" ></drink> </div>
The code in the controller
var mymodule=angular.module ("MyModule", []); Mymodule.controller (' Myctrl ', [' $scope ', function ($scope) {$ Scope.ctrlflavor= "88888";}]) Mymodule.directive ("Drink", function () {return{restrict: ' AE ', scope:{zk: ' = '}, Template: ' <input type= ' text ' Ng-model= "ZK" > '}})
In the HTML, there is a text box, in the template of the drink directive, there is also a text box, the contents of the two text boxes are two-way bound. That is, when the contents of the above text box change, the contents of the box below change as well.
3. "&": Pass the function from the parent scope and call it later
<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" > <div ng-controller= "Myctrl" > <greeting greet= "SayHello (name)" ></greeting> </div></span>
Controller code
var mymodule=angular.module ("MyModule", []); Mymodule.controller (' Myctrl ', [' $scope ', function ($scope) { $ Scope.sayhello=function (name) { alert ("Hello" +name); }]) Mymodule.directive ("Greeting", function () { return { restrict: ' AE ', scope:{ greet: ' & ' }, Template: ' <input type= ' text ' ng-model= ' userName '/><br/> ' + ' <button class= ' btn btn-default ' Ng-click= "greet ({name:username})" > ' + ' greeting</button><br/> '} });
This example means that a controller is bound in a Div, the controller defines a SayHello method, and a command named greeting is defined in the Div. The greet method of this instruction is associated with the SayHello of the parent scope, and then we have the scope of the greeting directive defined greet in the controller so that the functions in the parent scope are passed to the child scope. Above is the scope of the binding strategy of a simple example, learning Angularjs, to start from the foundation.
AngularJS--scope Binding policy