Configuring the Directive Scope

At times you may want to separate the scope inside a directive from the scope outside the directive. Doing so prevents the possibility of the directive changing values in the local controller. The directive definition allows you to specify a scope that creates an isolate scope. An isolate scope isolates the directive scope from the outer scope to prevent the directive from accessing the outer scope and the controller in the outer scope from altering the directive scope. For example, the following isolates the scope of the directive from the outside scope:

directive('myDirective', function() {
  return {
    scope: { },
    templateUrl: '/myDirective.html'
  };
});

Using this code, the directive has a completely empty isolate scope. However, you might want to still map some items in the outer scope to the directive’s inner scope. You can use the following prefixes to attribute names to make local scope variables available in the directive’s scope:

Image @: Binds a local scope string to the value of the DOM attribute. The value of the attribute will be available inside the directive scope.

Image =: Creates a bidirectional binding between the local scope property and the directive scope property.

Image &: Binds a function in the local scope to the directive scope.

If no attribute name follows the prefix, the name of the directive property is used. For example:

title : '@'

is the same as:

title: '@title'

The following code shows how to implement each of the different methods to map local values into a directive’s isolate scope:

angular.module('myApp', []).
  controller('myController', function($scope) {
    $scope.title="myApplication";
    $scope.myFunc = function(){
      console.log("out");
    };
  }).
  directive('myDirective', function() {
    return {
      scope: {title: '=', newFunc:"&myFunc", info: '@'},
      template: '<div ng-click="newFunc()">{{title}}: {{info}}</div>'
    };
  });

The following code shows how to define the directive in the AngularJS template to provide the necessary attributes to map the properties:

<div my-directive
     my-func="myFunc()"
     title="title"
     info="SomeString"></div>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.111.134