2016-08-24 148 views
0

嗨,我在angularjs工作。我在指令中遇到了一個問題。
我已經設置鏈接scope.user.name="amin shah" /點擊事件 ,並希望訪問該控制器中,這怎麼可能?Angularjs指令的指令,並訪問設定範圍VAR在控制器

var dataSourceDirective = angular.module('mydirective', []); 
dataSourceDirective.directive('dir', function() { 
    return { 
     restrict: 'C', 
     scope: true, 
     link: function ($scope, element, attrs) { 
      element.bind('click', function() { 
        $scope.user.name ="amin shah"; 
        $scope.$apply(); 
        $('.sourceType_panel').hide(); 
        $('#sourceType_1_panel').show(); 

      }); 
     } 
    } 
}); 

控制器代碼

$scope.demo = function() { 
     console.log($scope.user);` 
}, 

回答

1

你需要在你的指令來創建隔離範圍。 給定的控制器應該是此指令的父代。

var dataSourceDirective = angular.module('mydirective', []); 
dataSourceDirective.directive('dir', function() { 
    return { 
     restrict: 'C', 
     scope: {user:"=user"}, 
     link: function ($scope, element, attrs) { 
      element.bind('click', function() { 
        $scope.user.name ="amin shah"; 

      }); 
     } 
    } 
}); 

在HTML:

<div ng-copntroller='yourCtrl'> 
<dir user="user"></dir> 
</div> 

在控制器,你應該初始化user

OR

您使用$broadcast & $emit如果家長控制。

指令

Withing鏈接功能,您可以使用$rootScope.$emit('user_name_update',user);

並在控制器,你可以聽此事件

$scope.$on('user_name_update',function(data){ 

    console.log(user) // its should give your updated `user` object 
}) 
0

,首先你應該糾正你的鏈接方法,我想你不應該需要孩子在那兒喝。所以你也應該在指令中刪除你的作用域綁定。您可以使用鏈接方法訪問父級範圍。

app.directive('dir', function() { 
    return { 
     restrict: 'E', 
     link: function (scope, element, attrs) { 
      element.bind('click', function() { 
        scope.user.name ="amin shah"; 
        scope.$apply(); 

      }); 
     } 
    } 
}); 

,並在你的控制器,你可以定義這樣的範圍變量:

app.controller('MainCtrl', function($scope) { 

     $scope.user = { 
     name: '' 
    } 
    }); 

也應將此指令添加到HTML:

<dir>Element</dir> 
<p>{{user.name}}</p> 

這裏工作plunkr您應該點擊元素比你可以從指令中看到你的名字,但在父範圍內

https://plnkr.co/edit/umTdfukZ22hARoLjxdL3?p=preview