在angular.js中的指令中从控制器访问范围变量

时间:2015-11-13 17:52:44

标签: javascript angularjs

&name

在html中,

(function () {
'use strict';

angular.module('app')
    .controller('someController', ['$scope','localStorageService',someController])
    .directive('someDirective', someDirective)

function someController($scope, localStorageService){
    $scope.something = {
        someVar: localStorageService.get('someVar'),
    };
    console.log("someVar: " + $scope.something.someVar);//prints correct value
}

function someDirective(){
    return {
        template: {{something.someVar}}
    };
}

})();

被添加,我一直得到一个“参数'someController'不是一个函数,得到了未定义”,即使someController在打印到控制台时执行正常。

3 个答案:

答案 0 :(得分:2)

此处指令的模板声明中存在错误。

template: {{something.someVar}}缺少引号。

应该是:template: '{{something.someVar}}'

答案 1 :(得分:0)

你可以尝试一下吗? 这应该工作

.controller('someController',someController)
.directive('someDirective', someDirective);

someController.$inject = ['$scope','localStorageService'];

答案 2 :(得分:0)

将创建控制器和指令的行移动到函数声明下面:

function someController($scope, localStorageService){
    $scope.something = {
        someVar: localStorageService.get('someVar'),
    };
    console.log("someVar: " + $scope.something.someVar);//prints correct value
}

function someDirective(){
    return {
        template: {{something.someVar}}
    };
}

angular.module('app')
    .controller('someController', ['$scope','localStorageService',someController])
    .directive('someDirective', someDirective);