2

I have passed an object from controller to directive but when i am reading object in directive i am not able to, it seems in directive object is being read as string.Code is below , i wane to read City and State from the object.

Html File

<div ng-controller="WeatherController">    
<div weather ng-object="{{Object}}"></div>
</div>

Controller
.controller('WeatherController', ['$scope', function ($scope) {
   $scope.webpartData.OverviewData.Person.Address.City;
            $scope.Object = {
                City: '',
                State: ''
            };
            $scope.Object.City = 'TestCity';
            $scope.Object.State = 'TestState';         
        });
    })
}])


Directive


angular.module('WeatherModule', [])
.directive('Weather', ["$timeout", function($timeout) {
    return {
        restrict: 'EA',
        template: '<div id="weather"></div>',
        scope: {
            ngObject: '@ngObject'
        },
        link: function(scope, element, attrs) {
            scope.$watch('ngObject', function(value) {
                scope.ngObject = value;
            });
            $timeout(function() {
                console.log('Location' + scope.Object.City + ',' + scope.Object.State);
            }, 100);
        }
    };
}])
Kareem Elshahawy
  • 1,421
  • 1
  • 12
  • 28
  • at the moment i see object is diplaying as {"City":"TestCity","State":"TestState"} Which is not readable by scope.Object.City and scope.Object.State – Sumeet Sharma May 19 '15 at 11:10

2 Answers2

6

There are differences between @, = and & in referencing the directive scope members.

 1. "@"   (Text binding / one-way binding)
 2. "="   (Direct model binding / two-way binding)
 3. "&"   (Behaviour binding / Method binding)

@ means that the changes from the controller scope will be reflected in the directive scope but if you modify the value in the directive scope, the controller scope variable will not get affected.

@ always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}.

= is birectional so if you change the variable in directive scope, the controller scope variable gets affected as well

& is used to bind controller scope method so that if needed we can call it from the directive

In your case you may need to use = instead of @

Have a look on the following fiddle (It's not mine, but it have good and to the point illustration) http://jsfiddle.net/maxisam/QrCXh/

Some Related Questions also:

Community
  • 1
  • 1
Kareem Elshahawy
  • 1,421
  • 1
  • 12
  • 28
1

You should use "=" instead "@". And ng-object="Object" instead ng-object="{{Object}}".

Ivan Toncev
  • 532
  • 5
  • 15