anam
anam

Reputation: 3913

passing object value to directive instead of any other data variable

I am trying to customize this working http://jsfiddle.net/markcoleman/JNqqU/ ,in current working fiddle directly object is assigned . where i am trying to change it to $scope.obj.items . passing object to directive is not working .

do i need to write some $watch fo r the variable ??? i am getting dynamic value that's why i am trying to pass Object value with this .

Code ::

<a href="#" pop-over items="obj.items", title="Mode of transport">
   Show Pop over</a>

javascript Directive part ::

 scope: {
            items: '=',
            title: '@'
        }

Any suggestion ,

I am trying Below Fiddle http://jsfiddle.net/JNqqU/652/

Upvotes: 0

Views: 52

Answers (4)

Koti Panga
Koti Panga

Reputation: 3720

You need two changes:

Change in HTML items :: {{obj.items}}

Change in Controller default obj items should be assigned with empty array ( $scope.obj={items:[]}; ) as popOver's $compile is looking for scope.items

See this Working fiddle

Also your testing code {{items | json }} in template can be removed after your observation.

Upvotes: 1

Jai
Jai

Reputation: 74738

You can change your controller to this:

bootstrap.controller('maincnt', function ($scope) {
    $scope.obj = { // declare the scope object here with a blank items 
        items: []
    };
    $scope.updateitem = function () {
        alert('scope update called');
        $scope.obj.items = ['car', 'truck', 'plane', 'bike']; // now update here
    }
});

Checkout fiddle.

Upvotes: 2

Rasalom
Rasalom

Reputation: 3111

You don't need to wrap it into object, but don't 'rewrite' whole array in 'update' method, but push values into it:

bootstrap.controller('maincnt',function($scope){
    $scope.items = [];
    $scope.updateitem=function(){
        alert('scope update called');
        $scope.items.push('car', 'truck', 'plane', 'bike');
    }

});

http://jsfiddle.net/btfu30k2/1/

$watch isn't necessary too.

Upvotes: 1

Cory Silva
Cory Silva

Reputation: 2811

Yes you should be making a watcher.

$scope.$watchCollection('items', function (newValue, oldValue) {
  if (newValue) {
     buildTemplate(newValue);
  }
});

Note: I used watchCollection because it is an array. If it were an object or simple value $watch would be used instead.

Upvotes: 1

Related Questions