如何从`directive`控制器更新`$ scope`对象

时间:2015-06-26 20:00:47

标签: javascript angularjs angularjs-directive angularjs-scope prototypal-inheritance

我正在尝试从控制器更新$scope对象,但它没有更新。但在控制台中,我的状态正在升级。

这是我的代码:

var galleryMenu = ['$route', function ($route) {

    return {

        scope : true,

        replace : true,

        template : function () {

            var page = $route.current.className || 'home';

            return galleryMenuItem(page);

        },

        controller : function ($scope, $element) {

            $scope.galleryProject = function () {

                $scope.galleryShow = !$scope.galleryShow;
                console.log($scope.galleryShow) //gives me true, but `DOM` not updating.

            }


        }

    }

}];

1 个答案:

答案 0 :(得分:3)

您的指令正在使用scope: true,这意味着您已创建一个原型继承自父作用域的作用域。

然后,您的galleryShow对象应该遵循dot rule

$scope.model = {};
$scope.model.galleryShow = 'something';

那么在你的指令中你可以通过原型继承获得$scope.model对象,你可以通过$scope.model.galleryShow来改变它将改变父范围。

指令控制器

controller : function ($scope, $element) {
     $scope.galleryProject = function () {
         $scope.model.galleryShow = !$scope.galleryShow;
         console.log($scope.model.galleryShow) //gives me true, but `DOM` not updating.
     }
  }