简体   繁体   English

angularjs指令,无法传递变量

[英]angularjs directive, cannot pass variable

So I am trying to inject a dynamic template into a page using angularjs. 因此,我尝试使用angularjs将动态模板注入页面。 I initially tried to use ng-include which is great, however I require two way binding of the $scope & ng-include makes its own local copy so that cannot be used. 我最初尝试使用ng-include很棒,但是我需要$ scope和ng-include的两种方式绑定,使其自身具有本地副本,因此无法使用。

I have since tried to create a custom directive to load content dynamically, this works as expected when data is hard coded, however when I try pass a variable to the directive, it passes literally what is typed and not the value of the variable. 此后,我尝试创建一个自定义指令以动态加载内容,当对数据进行硬编码时,此指令可以按预期工作,但是,当我尝试将变量传递给指令时,它将按字面值传递而不是变量的值。

Controller 控制者

$scope.test = 'Yes!'

Directive 指示

Basically, I would like the templateUrl to have a dynamic value 基本上,我希望templateUrl具有动态值

materialAdmin.directive("prospectiveModal", function () {


var dynamicUrl = function(scope, element, attributes) {

            console.log('directive')
            console.log('scope')
            console.log(scope)
            console.log('element')
            console.log(element)
            console.log('attributes')
            console.log(attributes)
            return 'views/prospectives/options/booked.html'
        };

return {
    restrict: 'EA',
    scope: {
        'test': '=test',

    }
    ,
    templateUrl: dynamicUrl

};

}) })

HTML 的HTML

            {{test}}}
        <div prospective-modal test="{{test}}"></div>

console.log output is below console.log输出如下

prospectiveModal:""
test:"{{test}}"

If I change the html to something like 如果我将html更改为类似

<div prospective-modal test="test"></div>

then console.log is 然后console.log是

test:"test"

How can I get the value of the variable inside of the directive? 如何获得指令内部变量的值? It must be possible right? 一定有可能吧?

So I found a way to do this. 所以我找到了一种方法。

If you call ng-include in the view, it will create a local scope copy. 如果在视图中调用ng-include ,它将创建本地作用域副本。 However it seems if you create it inside the directive, it does not. 但是,如果您在指令中创建它,似乎没有。 So I did something like this: 所以我做了这样的事情:

materialAdmin.directive("prospectiveModal", function () {

return {
    restrict: 'EA',
    scope: false,
    template: "<div ng-include='subMenu[subOption].path'></div>"

};

})

Then in the view 然后在视图中

<prospective-modal ></prospective-modal>

$scope has access to subMenu[subOption].path so when that value is changed, so is the template. $scope可以访问subMenu[subOption].path因此更改该值时,模板也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM