Isolate Scope "=" anchored and anchored AngularJS notation

How to create a two-way binding with a nested property in the selection area with dotted notation. I thought that 'myObject.data': "=data" would work, but it is not. I do not want to bind all myObject . I know I can do some hours, but 'myObject.data' seems cleaner.

 .directive("myDirective", [function() { return { restrict: "E", scope: { 'myObject.data': "=data" }, link: function (scope, element, attrs) { scope.myObject = { data: "myValue" }; } }; }]) 
+6
source share
2 answers

Isolated areas are usually only useful with templates; they should not be used as a way to declare how you want your directive attributes to be interpreted. This is due to the fact that most directives that do not have a template usually need the semantics of either a child’s area or a direct area of ​​their environment.

In your case, you probably don't even need $ watch, because object references are something that allow you to bind 2-way data, but without your complete code, I cannot be sure.

If you want translations for the selected area semantics to be just normal:

 @name -> attrs.name =name -> $scope.$eval(attrs.name); &name -> function() { return $scope.$eval(attrs.name); } 

EDIT 2:

After your comment, I came up with this plunker . To preserve two-way data binding, you must use ".". in the ng model declaration. This is because two-way data binding does not work for value types, because they are immutable. You cannot change the value 100, for example. You need to pass an object of a reference type and hang up the values ​​that you are changing. Your desire to indicate the full path to the value in the definition of an isolated area is not possible based on the principles that provide the possibility of two-way data binding.

JavaScript:

 angular.module('plunker', []) .directive('twoWay', function() { return { restrict: 'E', template: '<div><input ng-model="thing.name" type="text" /></div>', scope: { thing: "=" }, link: function(scope, element, attrs) { } }; }) .controller('MainCtrl', function($scope) { $scope.data = { name: "World" }; }); 

HTML:

  <body ng-controller="MainCtrl"> <p>Hello {{data.name}}!</p> <two-way thing="data"></two-way> </body> 
+8
source

In these cases, I use the following:

 .directive("myDirective", [function() { return { restrict: "E", scope: { data: "=" }, controller: function($scope){ $scope.dot = $scope //<--- here is the trick } }; }]) 

Then you can always change the data in the directive region from the inherited region with dot.data = 'whatever' without setting observers.

Not very elegant, but it works great in cases where you do not use the controller as syntax and don’t want the $parent nightmare.

0
source

All Articles